5

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() // <- ???
Shouichi
  • 1,090
  • 1
  • 10
  • 25

3 Answers3

5

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(_))
Ben Reich
  • 16,222
  • 2
  • 38
  • 59
  • Thank you. Thought this might be what I wanted, I got `error: missing parameter type for expanded function ((x$1) => System.out.println(x$1))`. Any idea? – Shouichi Dec 02 '15 at 08:28
  • @Shouichi works for me with the 2.11.4 REPL, as written above. I suppose it truly is an experimental feature! Maybe try playing around with the different syntax variants (e.g. `x => f(x)`, `f _`, `f(_)`, and `f`). Worst comes to worst just implement the `IntConsumer` interface. – Ben Reich Dec 02 '15 at 08:54
  • Seems like it really is! I don't want to use experimental feature in the production system and implement Java's stream interface. Than you again :) – Shouichi Dec 02 '15 at 09:03
2

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))
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • Thank you but what I need to do is handling Java stream API, not achieving the same thing. – Shouichi Dec 02 '15 at 07:59
  • 1
    So you need to precise your question – cchantep Dec 02 '15 at 08:12
  • 1
    @Shouichi so you should be more specific in what are you trying to achieve. In Java, you have to use special operators to access function as a variable. In Scala, there is no need for special operators. For example, `System.out::println` will be `java.lang.System.out.println`, nothing more. – Everv0id Dec 02 '15 at 08:12
0

The equivalent for method reference in scala would be the following:

IntStream.range(1, 4)
  .forEach(System.out.println _)
pezetem
  • 2,503
  • 2
  • 20
  • 38