Somasundaram Sekar
Somasundaram Sekar

Reputation: 5524

Java 8 Stream from scala code

I'm trying to use Java 8 Stream from scala code as below and stuck with an compilation error.

any help appreciated!!

def sendRecord(record: String): Unit throws Exception

bufferedReader.lines().forEach(s => sendRecord(s))

Cannot resolve forEach with such signature, expect: Consumer[_ >: String], actual: (Nothing)

PS: though there is some indication that it is almost straight forward like https://gist.github.com/adriaanm/892d6063dd485d7dd221 it doesn't seem to work. I'm running Scala 2.11.8

Upvotes: 4

Views: 5486

Answers (4)

Łukasz
Łukasz

Reputation: 8663

Look at top of the file you linked in your question. It mentions -Xexperimental flag. If you run scala compiler or repl with this flag scala functions will be translated to java equivalents. Another option is to just pass in java function manually.

scala> java.util.stream.Stream.of("asd", "dsa").map(new java.util.function.Function[String, String] { def apply(s: String) = s + "x" }).toArray
res0: Array[Object] = Array(asdx, dsax)

you can also create (implicit) conversion to wrap scala functions for you.

You can also wait for scala 2.12, with this version you won't need the flag anymore.

Update

As scala 2.12 is out, the code in question would just compile normally.

Upvotes: 4

Milad Khajavi
Milad Khajavi

Reputation: 2859

In Scala 2.12 you can work with Java streams very easily:

import java.util.Arrays

val stream = Arrays.stream(Array(1, 2, 3, 4, 6, 7))
stream
  .map {
    case i: Int if i % 2 == 0 => i * 2
    case i: Int if i % 2 == 1 => i * 2 + 2
  }
  .forEach(println)

Upvotes: 3

user140547
user140547

Reputation: 8200

The problem is that that expression in scala does not automatically implement the expected java functional interface Consumer.

See these questions for details how to solve it. In Scala 2.12,it will probably work without conversions.

Upvotes: 2

chengpohi
chengpohi

Reputation: 14217

You can convert toiterator to iterate java Stream, like:

import scala.collection.JavaConverters._
bufferedReader.lines().iterator.asScala.forEach(s => sendRecord(s))

Upvotes: 6

Related Questions