如何将 Java 流转换为 Scala 数组?
How to convert a Java Stream to Scala Array?
给出
new Scanner(is)
.tokens()
.map(_.toInt)
.toArray[Int]((_: Int) => Array.ofDim[Int](100000))
我遇到编译错误
Error:(40, 12) no type parameters for method map: (x: 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)
这里有什么问题?
编译器正在尝试为 Stream#map
查找 R
类型参数。因为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)
给出
new Scanner(is)
.tokens()
.map(_.toInt)
.toArray[Int]((_: Int) => Array.ofDim[Int](100000))
我遇到编译错误
Error:(40, 12) no type parameters for method map: (x: 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)
这里有什么问题?
编译器正在尝试为 Stream#map
查找 R
类型参数。因为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)