为什么我不能将Scala的Function1隐式转换为java.util.function.Function?

时间:2015-12-18 12:58:22

标签: java scala java-8 implicit

我正在尝试创建Scala的Function1到java.util.function.Function的隐式转换。

这是我的代码:

object Java8ToScala extends App {

  implicit def javaFuncToScalaFunc[T, R](func1: Function[T, R]): function.Function[T,R] = {
    new function.Function[T, R] {
      override def apply(t: T): R = func1.apply(t)
    }
  }

  val javaFunc:function.Function[String,Int] = (s:String) => s.length

  println(javaFunc.apply("foo")) // this works

  private val strings = new util.ArrayList[String]()
  println(strings.stream().map(javaFunc).collect(Collectors.toList())) // this doesn't work

}

编译器消息很难理解:

[error] /xxx/Java8ToScala.scala:74: no type parameters for method map: (x$1: java.util.function.Function[_ >: String, _ <: R])java.util.stream.Stream[R] exist so that it can be applied to arguments (java.util.function.Function[String,Int])
[error]  --- because ---
[error] argument expression's type is not compatible with formal parameter type;
[error]  found   : java.util.function.Function[String,Int]
[error]  required: java.util.function.Function[_ >: String, _ <: ?R]
[error] Note: String <: Any, but Java-defined trait Function is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error]     .map(javaFunc).collect(Collectors.toList()))
[error]      ^
[error] /xxx/Java8ToScala.scala:74: type mismatch;
[error]  found   : java.util.function.Function[String,Int]
[error]  required: java.util.function.Function[_ >: String, _ <: R]
[error]     .map(javaFunc).collect(Collectors.toList()))
[error]          ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 7 s, completed Dec 18, 2015 10:51:15 AM

2 个答案:

答案 0 :(得分:3)

只是Scala类型推断失败了,虽然我不明白为什么:它似乎正在寻找R扩展AnyRef。如果您使用此类型,则为works,例如val javaFunc: function.Function[String,String] = (s:String) => s

但是,它并没有在任何地方获得上限:同时使用map[Int]显式works

答案 1 :(得分:0)

使用以下隐式转换:

implicit def javaFuncToScalaFunc[T, R](func1: function.Function[T, R]): Function[T,R] = {
  new Function[T, R] {
    override def apply(t: T): R = func1.apply(t)
  }
}

在您的代码中,您有一个从Scala函数到Java函数的隐式转换,但您应该从Java函数到Scala函数进行隐式转换。