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

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

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


当前回答

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

其他回答

你可以试试这个:

var a = Array<Int>(5){0}

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

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)

你可以这样做:

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

or

val numbers = arrayOf<Int>(10, 20, 30, 40, 50)

also

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

简单的方法:

整数:

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

保持所有数据类型

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

通过这种方式,可以在koltin中初始化int数组。

 val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)