Why var i start at 0 in Kotlin?

I read the sample code val asc = Array(5, { i -> (i * i).toString() }).

Result ["0", "1", "4", "9", "16"].

But it is very strange to me why var I start with 0 in the expression { i -> (i * i).toString() }

+4
source share
2 answers

The constructor you are using is as follows:

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

It takes an index that begins with0 for the array, so { i -> (i * i).toString() }with 0as an argument leads to 0.

You can check this with this code if there is any doubt:

fun main(args: Array<String>) {
    val func: (Int) -> (String) = { i -> (i * i).toString() }
    println(func(0))
}
+6
source

Arrays in Kotlin (like many languages, including C, C ++, C #, and Java) use zero-base arrays. This means that the first element is in position 0.

(Cf. Fortran, where arrays are based on 1).

+5
source

Source: https://habr.com/ru/post/1685650/


All Articles