Pavel Orekhov
Pavel Orekhov

Reputation: 2178

How do I use java 8's stream collect from scala 2.11?

I have this piece of code:

import java.util.stream._
import java.util.function._

final case class AbcTest(value: String)

def funToFunction[InT, OutT](fun: InT => OutT): Function[InT, OutT] = new Function[InT, OutT] {
  override def apply(t: InT): OutT = fun(t)
}

def main(args: Array[String]): Unit = {
  Stream.of("a", "b", "c")
    .map[AbcTest](funToFunction((v: String) => AbcTest(v)))
    .collect(Collectors.toList())
}

And it fails with this error message:

    Error:(43, 27) type mismatch;
 found   : java.util.stream.Collector[Nothing,?0(in method main),java.util.List[Nothing]] where type ?0(in method main)
 required: java.util.stream.Collector[_ >: test.AbcTest, ?, ?]
Note: Nothing <: Any, but Java-defined trait Collector is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
      .collect(Collectors.toList)

I don't understand what's happening, please help.

Upvotes: 2

Views: 1672

Answers (1)

sarveshseri
sarveshseri

Reputation: 13985

Well... from what I have seen the following works absolutely fine, remember to just help a little in some type inferencing

import java.util.{stream => jStream}
import java.util.{function => jFunction}

def funToFunction[InT, OutT](fun: InT => OutT): jFunction.Function[InT, OutT] =
  new jFunction.Function[InT, OutT] {
    override def apply(t: InT): OutT = fun(t)
  }

final case class AbcTest(value: String)

val javaList =
  jStream.Stream.of("a", "b")
    .map[AbcTest](funToFunction((s: String) => AbcTest(s)))
    .collect(jStream.Collectors.toList[AbcTest])

Upvotes: 6

Related Questions