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

我怕爱的太早我们不能终老 提交于 2020-06-17 00:10:24

问题


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.


回答1:


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])


来源:https://stackoverflow.com/questions/54255632/how-do-i-use-java-8s-stream-collect-from-scala-2-11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!