在Java中,数组可以这样初始化:

int numbers[] = new int[] {10, 20, 30, 40, 50}

Kotlin的数组初始化是怎样的?


当前回答

Kotlin有专门的类来表示基本类型的数组,没有装箱开销。例如- IntArray, ShortArray, ByteArray等。我需要说明,这些类与父Array类没有继承关系,但它们具有相同的方法和属性集。它们中的每一个都有相应的工厂函数。所以,要在Kotlin中初始化一个数组,你只需要键入以下内容:

val myArr: IntArray = intArrayOf(10, 20, 30, 40, 50)

...或者这样:

val myArr = Array<Int>(5, { i -> ((i + 1) * 10) })

myArr.forEach { println(it) }                            // 10, 20, 30, 40, 50

现在你可以使用它:

myArr[0] = (myArr[1] + myArr[2]) - myArr[3]

其他回答

I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this: val array = Array(5, { i -> i }), the initial values assigned are [0,1,2,3,4] and not say, [0,0,0,0,0]. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() }) produces an answer of ["0", "1", "4", "9", "16"]

你可以像这样创建一个Int数组:

val numbers = IntArray(5, { 10 * (it + 1) })

5是Int数组的大小。函数是元素init函数。“it”范围在[0,4],加上1 make范围在[1,5]

原点函数为:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

定义在Arrays.kt中的IntArray类

在Kotlin中有几种初始化数组的方法:

劳动力素质():

var myarray = arrayOf(1,2,3,4,5)

劳动力素质():

var myarray = arrayOf<Int>(1,2,3,4,5)

使用Array构造函数:

val num = Array(3, {i-> i*1})

内置的工厂方法:

val num1 = intArrayOf(1, 2, 3, 4)
//For Byte Datatype
val num2 = byteArrayOf()
//For Character Datatype
val num3 = charArrayOf()
//For short Datatype
val num4 = shortArrayOf()
//For long
val num5 = longArrayOf()

我的回答补充了@maroun,这些是初始化数组的一些方法:

使用数组

val numbers = arrayOf(1,2,3,4,5)

使用严格的数组

val numbers = intArrayOf(1,2,3,4,5)

混合矩阵类型

val numbers = arrayOf(1,2,3.0,4f)

嵌套数组

val numbersInitials = intArrayOf(1,2,3,4,5)
val numbers = arrayOf(numbersInitials, arrayOf(6,7,8,9,10))

能够从动态代码开始

val numbers = Array(5){ it*2}

你可以简单地使用现有的标准库方法,如下所示:

val numbers = intArrayOf(10, 20, 30, 40, 50)

使用一个特殊的构造函数可能是有意义的:

val numbers2 = IntArray(5) { (it + 1) * 10 }

你传递一个大小和一个lambda来描述如何初始化这些值。以下是文档:

/**
 * Creates a new array of the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> Int)