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() }
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With