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

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

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


当前回答

当初始化下面的字符串检查

val strings = arrayOf("January", "February", "March")

我们可以使用原始int数组专用的arrayOf方法简单地初始化它:

val integers = intArrayOf(1, 2, 3, 4)

其他回答

值得一提的是,当使用kotlin内置程序(例如intArrayOf(), longArrayOf(), arrayOf()等)时,对于给定的大小,您不能使用默认值(或所有值为所需值)初始化数组,相反,您需要通过根据类构造函数调用来进行初始化。

// Array of integers of a size of N
val arr = IntArray(N)

// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }

简单的方法:

整数:

var number = arrayOf< Int> (10,20,30,40,50)

保持所有数据类型

var number = arrayOf(10, "string value", 10.5)

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

详见Kotlin -基本类型。

你也可以提供一个初始化函数作为第二个参数:

val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]

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"]

我的回答补充了@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}