代码之家  ›  专栏  ›  技术社区  ›  Abhijit Sarkar

如何将Java流转换为Scala数组?

  •  1
  • Abhijit Sarkar  · 技术社区  · 6 年前

    鉴于

    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)
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Abhijit Sarkar    6 年前

    编译器正在尝试查找 R 的类型参数 Stream#map map 是一个 Function[String,Int] ,并且它必须与 Function[_ >: String, _ <: R] 地图 ),这是有限制的 Int <: R 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)
    
    推荐文章