为什么 scala WrappedArray[Int](null,null) returns 0 应用时,发生了什么?

Why scala WrappedArray[Int](null,null) returns 0 when apply, what happened?

在 sparkSql UDAF 函数中工作时,我发现我的某些输入列意外地从 null 变为 0。

通过一些 REPL 实践,事实证明行为是 scala 2.10.5 的。

如下所示代码快照

import scala.collection.mutable

val wa = mutable.WrappedArray.make[Int](Array(null, null))

wa

wa(1)

你能请使用 scala 的家人帮助解释为什么以及幕后发生了什么吗?

您调用了方法 make[Int],声明如下:

def make[T](x: AnyRef): WrappedArray[T] = (x match {
    case null              => null
    case x: Array[AnyRef]  => new ofRef[AnyRef](x)
    case x: Array[Int]     => new ofInt(x)
    case x: Array[Double]  => new ofDouble(x)
    case x: Array[Long]    => new ofLong(x)
    case x: Array[Float]   => new ofFloat(x)
    case x: Array[Char]    => new ofChar(x)
    case x: Array[Byte]    => new ofByte(x)
    case x: Array[Short]   => new ofShort(x)
    case x: Array[Boolean] => new ofBoolean(x)
    case x: Array[Unit]    => new ofUnit(x)
  }).asInstanceOf[WrappedArray[T]]

在您的例子中 xArray(null, null),它是 Array[AnyRef] 的实例,因此 make 创建 return 的 class 实例ofRef[AnyRef] 声明为:

final class ofRef[T <: AnyRef](val array: Array[T]) extends WrappedArray[T] with Serializable {
  lazy val elemTag = ClassTag[T](arrayElementClass(array.getClass))
  def length: Int = array.length
  def apply(index: Int): T = array(index).asInstanceOf[T]
  def update(index: Int, elem: T) { array(index) = elem }
}

当您调用 wa(1) 时,您会调用此 class 的方法 apply,因为您的第二个元素是 null,它将 return 0, 因为 null.asInstanceOf[Int] returns 0.