什么是Scala Array.apply的魔力 [英] what is magic of Scala Array.apply

查看:45
本文介绍了什么是Scala Array.apply的魔力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从scala-2.10.4的array.scala中,将 Array 定义为

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()
}

请注意,apply方法将引发异常!对于陪伴对象Arrry,我找到以下代码:

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
  }

我知道有一个隐式参数是 ClassTag [T] ,令我感到惊讶的是

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

新数组[T](xs.length)

new Array[T] (xs.length)

已编译.通过反编译Array.class,我发现该行被翻译为:

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?

谢谢张

推荐答案

Scala Array 类只是运行时的伪包装,因此您可以在Scala中使用数组.您可能会感到困惑,因为 Array 类上的那些方法会引发异常.他们这样做的原因是,这样一来,如果您最终使用了伪类,它就会崩溃,因为实际上它应该使用的是Java运行时数组,该数组没有像Scala这样的适当容器类.您可以看到

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编译器的魔力使数组在后台与Java运行时一起工作.

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

这篇关于什么是Scala Array.apply的魔力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆