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

其他回答

值得一提的是,当使用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 }

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

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 id_1: Int = 1
val ids: IntArray = intArrayOf(id_1)

你也可以使用ArrayList来填充,然后返回一个数组。 方法将在列表中添加10,000个Item类型的元素,然后返回一个Item数组。

private fun populateArray(): Array<Item> {
    val mutableArray = ArrayList<Item>()
    for (i in 1..10_000) {
        mutableArray.add(Item("Item Number $i" ))
    }
    return mutableArray.toTypedArray()
}

Item数据类看起来像这样:

data class Item(val textView: String)

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