scala陣列與java陣列對比

鴨梨山大哎發表於2020-11-27

java陣列不是個類,scala陣列是類
java定義

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

scala定義

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
  }

相關文章