簡體   English   中英

為什么我不能將Scala的Function1隱式轉換為java.util.function.Function?

[英]Why can't I implicit convert Scala's Function1 to java.util.function.Function?

我正在嘗試創建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

這只是Scala的類型推斷失敗了,雖然我不明白為什么它似乎是在尋找一個R延伸AnyRef 如果使用這樣的類型,它可以工作 ,例如val javaFunc: function.Function[String,String] = (s:String) => s

但是,它沒有在任何地方獲得上限:使用map[Int]明確地起作用

使用以下隱式轉換:

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函數進行隱式轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM