Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the var i begin with 0 in Kotlin?

Tags:

kotlin

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

The result is ["0", "1", "4", "9", "16"].

But I'm very strange why the var i begin with 0 in expression { i -> (i * i).toString() }

like image 617
HelloCW Avatar asked Dec 18 '22 04:12

HelloCW


1 Answers

The constructor you're using looks like this:

 /**
 * 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 the index which starts at 0 for an array, thus { i -> (i * i).toString() } with 0 as an argument results in 0.

You can check it with this code if there's any doubt:

fun main(args: Array<String>) {
    val func: (Int) -> (String) = { i -> (i * i).toString() }
    println(func(0))
}
like image 174
s1m0nw1 Avatar answered Jan 10 '23 16:01

s1m0nw1