Eevy Eevy - 16 days ago 7
Scala Question

Scala to Java8 stream 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 fine

What's wrong?

Answer

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

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

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

Try this;

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