我是Kotlin的新手,很难理解init function在数组上下文中是如何工作的。具体来说,如果我尝试使用以下方式创建String
类型的数组:
val a = Array<String>(a_size){"n = $it"}
这有效,但"n = $it"
是什么意思?这看起来不像init
函数,因为它在花括号内而不在括号内。
如果我想要一个Int
数组init
函数或花括号内的部分是什么样的?
答案 0 :(得分:8)
您正在使用初始化程序调用构造函数:
/**
* Creates a new array with 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) -> T)
因此,您将函数传递给将为每个元素调用的构造函数。 a
的结果将是
[
"n = 0",
"n = 1",
...,
"n = $a_size"
]
如果您只想创建一个包含所有0
值的数组,请执行以下操作:
val a = Array<Int>(a_size) { 0 }
或者,您可以通过以下方式创建数组:
val a = arrayOf("a", "b", "c")
val b = intArrayOf(1, 2, 3)