地图操作中的 Scala 类型不匹配

Scala type mismatch in map operation

我正在尝试在下面的代码中对 Spark DStream 进行映射操作:

val hashesInRecords: DStream[(RecordKey, Array[Int])] = records.map(record => {
      val hashes: List[Int] = calculateIndexing(record.fields())
      val ints: Array[Int] = hashes.toArray(Array.ofDim[Int](hashes.length))
      (new RecordKey(record.key, hashes.length), ints)
    })

代码在 IntelliJ 中看起来不错,但是当我尝试构建时出现一个我不太理解的错误:

Error:(53, 61) type mismatch;
 found   : Array[Int]
 required: scala.reflect.ClassTag[Int]
      val ints: Array[Int] = hashes.toArray(Array.ofDim[Int](hashes.length))

即使我像这样在地图操作中添加类型后,此错误仍然存​​在:

records.map[(RecordKey, Array[Int])](record => {...

这应该可以解决您的问题,它还避免了 List.length 的调用,即 O(N),并且使用 Array.length 而不是 O(1).

val hashesInRecords: DStream[(RecordKey, Array[Int])] = records.map { record =>
  val ints = calculateIndexing(record.fields()).toArray
  (new RecordKey(record.key, ints.length), ints)
}