我有这段代码:
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())
}
它失败并显示以下错误消息:
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)
我不明白发生了什么,请帮忙。
答案 0 :(得分:3)
嗯...从我所看到的以下内容来看,一切都很好,请记住只是在某种类型推断方面有所帮助
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])