Kotlin Array初始化函数

Ara*_*raf 4 arrays kotlin

我是Kotlin的新手,很难理解init函数在Array的上下文中是如何工作的.具体来说,如果我正在尝试String使用以下类型的数组:

val a = Array<String>(a_size){"n = $it"}
Run Code Online (Sandbox Code Playgroud)
  1. 这有效,但"n = $it"意味着什么?这看起来不像init函数,因为它在花括号内而不在括号内.

  2. 如果我想要一个数组,Int那个init函数或花括号里面的部分是什么样的?

nha*_*man 9

您正在使用初始化程序调用构造函数:

/**
 * 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)

  • 在Java中,这将产生一个包含所有"0"值的列表.在Kotlin中,您必须明确指定. (2认同)
  • 您将需要创建具有可空值的数组,或者为该类型提供默认的非null值. (2认同)