scala数组与java数组对比

java数组不是个类,scala数组是类
java定义

int[] a = new int[]{1, 2, 5};

scala定义,scala这个实际是个语法糖,调用了apply方法

val a=Array(1,2,5)

源码上

scala

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

  // The element at given index.
  def apply(i: Int): T = throw new Error()

  // Update the element at given index.
  def update(i: Int, x: T) { throw new Error() }

  //Clone the Array.
  override def clone(): Array[T] = throw new Error()
}

针对不同的泛型T,scala有不同的实现,比如针对Int

 /** Creates an array of `Int` objects */
  // Subject to a compiler optimization in Cleanup, see above.
  def apply(x: Int, xs: Int*): Array[Int] = {
    val array = new Array[Int](xs.length + 1)
    array(0) = x
    var i = 1
    for (x <- xs.iterator) { array(i) = x; i += 1 }
    array
  }

java 源码
java 找不到Array的源码~!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页