为什么我在Kotlin中以0开头?
我读了一个示例代码val asc = Array(5, { i -> (i * i).toString() })
。
结果是["0", "1", "4", "9", "16"]
。
但我很奇怪,为什么var我以expression { i -> (i * i).toString() }
你正在使用的构造函数如下所示:
/** * 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)
它使用从0
开始的数组作为数组,因此以0
作为参数的{ i -> (i * i).toString() }
结果为0
。
如果有任何疑问,您可以使用此代码进行检查:
fun main(args: Array<String>) { val func: (Int) -> (String) = { i -> (i * i).toString() } println(func(0)) }
Kotlin中的数组(像许多语言,包括C,C ++,C#和Java)都使用基于零的数组 。 这意味着第一个元素在位置0。
(参见Fortran,其中数组是基于1的)。