我如何使用 java 8 的流从 Scala 2.11 收集?

hey*_*you 2 generics scala

我有这段代码:

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())
}
Run Code Online (Sandbox Code Playgroud)

它失败并显示此错误消息:

    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)
Run Code Online (Sandbox Code Playgroud)

我不明白发生了什么,请帮忙。

Sar*_*ngh 6

嗯...从我所看到的以下工作非常好,记得在某些类型推理中提供一点帮助

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])
Run Code Online (Sandbox Code Playgroud)