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