Kotlin数组初始化函数

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

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

  2. 如果我想要一个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) 

因此,你正在传递一个函数给构造函数,这个函数将被调用给每个元素。 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)