what is magic of Scala Array.apply

1.3k views Asked by At

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

2

There are 2 answers

0
Noah On

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
0__ On

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).