4

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

4 Answers 4

6

You can convert toiterator to iterate java Stream, like:

import scala.collection.JavaConverters._
bufferedReader.lines().iterator.asScala.forEach(s => sendRecord(s))
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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)

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.