what is magic of Scala Array.apply

允我心安 提交于 2019-12-10 18:49:53

问题


From array.scala of scala-2.10.4, The Array is defined as

final class Array[T](_length: Int) extends java.io.Serializable with java.lang.Cloneable {    
  /** The length of the array */
  def length: Int = throw new Error()
  def apply(i: Int): T = throw new Error()
  def update(i: Int, x: T) { throw new Error() }
  override def clone(): Array[T] = throw new Error()
}

Please note, the apply method will throw an exception! And for the accompany object Arrry, I find the following codes:

  def apply[T: ClassTag](xs: T*): Array[T] = {
    val array = new Array[T](xs.length)
    var i = 0
    for (x <- xs.iterator) { array(i) = x; i += 1 }
    array
  }

I know there is an implicit parameter which is ClassTag[T], what make me surprised is how

new Array[T] (xs.length)

is compiled. By decompiling the Array.class, I find that line is translated to :

public <T> Object apply(Seq<T> xs, ClassTag<T> evidence$2)
{
    // evidence$2 is implicit parameter
    Object array = evidence$2.newArray(xs.length());
    ...  
}

I am really confused by this kind of translation, what is the rule under the hood?

Thanks Chang


回答1:


The Scala Array Class is just a fake wrapper for the runtime so you can use arrays in Scala. You're probably confused because those methods on the Array class throw exceptions. The reason they did this is so that if you actually end up using the fake class it blows up since really it should be using the java runtime array, which does not have a proper container class like Scala. You can see how the compiler handles it here. When your using arrays in Scala you're probably also using some implicits from predef like ArrayOps and WrappedArray for extra helper methods.

TLDR: Scala compiler magic makes arrays work with the java runtime under the hood.




回答2:


On the JVM arrays are exempt from type-erasure, e.g. at runtime instead of Array[_] there is a difference between Array[Int], Array[String] and Array[AnyRef] for example. Unlike Java, Scala can handle this mostly transparently, so

class Foo {
  val foo = new Array[Int](123)
}

has a direct byte-code invocation for creating the integer array, whereas

class Bar[A](implicit ev: reflect.ClassTag[A]) {
  val bar = new Array[A](123)
}

is solved by using the implicit type evidence parameter of type ClassTag[A] so that at runtime the JVM can still create the correct array. This is translated into the call you saw, ev.newArray(123).



来源:https://stackoverflow.com/questions/31001175/what-is-magic-of-scala-array-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!