Scala on Java8 thread compatibility issue
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) })
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(_))
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) } )