Kotlin Array初始化函数

时间:2017-06-02 09:30:02

标签: arrays kotlin

我是Kotlin的新手,很难理解init function在数组上下文中是如何工作的。具体来说,如果我尝试使用以下方式创建String类型的数组:

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

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

1 个答案:

答案 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)