log.info(x.toString)) gives Error:(21, 16) miss...">

Scala on Java8 thread compatibility issue

(scala)

Files.walk(Paths.get("")).forEach(x => log.info(x.toString))

gives

Error:(21, 16) missing parameter type
  .forEach(x => log.info(x.toString))
           ^

and (java8)

Files.walk(Paths.get("")).forEach(x -> System.out.println(x.toString()));

works great

What's wrong?

+4
source share
3 answers

stream.forEach(x -> foo()) in java - syntax sugar for

stream.forEach(
  new Consumer<Path> { public void accept(Path x) { foo(); } }
)

This is not exactly the same as x => ...in scala, which is an instance Function[Path,Unit].

Try it;

Files.walk(Paths.get(""))
  .forEach(new Consumer[Path] { def accept(s: Path) = println(s) })
+8
source

Alternative route: instead of converting the scala function to a java user, you can convert the java stream to a scala stream and use regular scala functions.

scala> import scala.collection.JavaConverters._
scala> import java.nio.file._
scala> val files = Files.walk(Paths.get("/tmp")).iterator.asScala.toStream
files: scala.collection.immutable.Stream[java.nio.file.Path] = Stream(/tmp, ?)
files.foreach(println(_))
+1
source

Scala 2.12 Java 8, Scala 2.12; 2.12:

Files.walk(Paths.get("")).forEach(x => System.out.println(x.toString))

2.11, scala-java8-compat.

libraryDependencies += "org.scala-lang.modules" %% "scala-java8-compat" % "0.8.0"

:

import scala.compat.java8.FunctionConverters._
Files.walk(Paths.get("")).forEach( asJavaConsumer { x => println(x.toString) } )
0
source

Source: https://habr.com/ru/post/1626646/


All Articles