简体   繁体   中英

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

You can convert to iterator to iterate java Stream , like:

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

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM