给予
new Scanner(is)
.tokens()
.map(_.toInt)
.toArray[Int]((_: Int) => Array.ofDim[Int](100000))
我收到一个编译错误
Error:(40, 12) 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])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : java.util.function.Function[String,Int]
required: java.util.function.Function[_ >: String, _ <: ?R]
Note: String <: Any, but Java-defined trait Function is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
.map(_.toInt)
Error:(40, 18) type mismatch;
found : java.util.function.Function[String,Int]
required: java.util.function.Function[_ >: String, _ <: R]
.map(_.toInt)
这是怎么了?
答案 0 :(得分:1)
编译器正在尝试为R
找到Stream#map
类型的参数。由于map
的参数是Function[String,Int]
,并且必须与Function[_ >: String, _ <: R]
兼容(来自map
的签名),因此存在约束Int <: R
。但是因为它是Java方法,所以还有一个约束R <: Object
(至少我认为是这样)。因此,没有合适的R
。
在这种情况下,错误消息不是很好,因为它没有给出第二个约束。
要修复,正如我在评论中提到的那样,您可以只使用mapToInt
,但实际上还有一个更糟糕的错误消息,绝对应该修复(我报告了一个问题):指定map[Int]
结果在
type mismatch;
found : Array[Int]
required: Array[Int]
Note: Int >: Int, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Int`. (SLS 3.2.10)