I need to handle Java 8 stream from Scala. What's the equivalent of Java 8 ::
operator in Scala?
// Java
IntStream.range(1, 4)
.forEach(System.out::println);
// Scala
IntStream.range(1, 4)
.forEach() // <- ???
You can use -Xexperimental
when compiling or running the REPL in order to access the experimental feature of converting Scala functions into the desired Java SAMs:
IntStream.range(1, 4).forEach(System.out.println(_))
This is as simple as:
scala> (1 to 4).foreach(println)
1
2
3
4
In Scala, referencing a method without providing an argument, such as:
def fn(arg: SomeType)
(collection_of_some_type).foreach(fn)
is desugared into
(collection_of_some_type).foreach(fn(_))
which in turn translates to:
(collection_of_some_type).foreach(next_entry => fn(next_entry))
The equivalent for method reference in scala would be the following:
IntStream.range(1, 4)
.forEach(System.out.println _)