2017-06-02 152 views
2

我是Kotlin的新手,难以理解init function如何在阵列环境中工作。特别是,如果我想使用String类型的数组进行:Kotlin Array init函数

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

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

回答

7

你调用一个初始化构造函数:

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

如果我不想用任何值初始化数组会怎么样?这个Java片段的Kotlin相当于ArrayList lst = new ArrayList (10);' – Araf

+2

在Java中,这将产生一个包含所有'0'值的列表。在Kotlin中,你必须明确地指定它。 – nhaarman

+0

我明白了。但我正在编写一个树枝模板的过程中,我试图推广各种数据类型的数组创建语法。所以我想要的东西是:'Array <{{TYPE}}>(a_size){{{GENERAL_INITIALIZER}}}'。 这是可能的当前语法? – Araf