Kotlin allows us to declare and initialize an array with a lambda expression. The array constructor takes two parameters: the size of the array and a lambda expression. If the array is an IntArray, the expression takes an integer and returns an integer as well:
public inline constructor(size: Int, init: (Int) -> Int)
Take a look at the following example. Here, intArray has 5 elements, and each element is initialized with an incrementing value that starts from 1:
fun arrayWithLambda(){
val intArray = IntArray(5) { it }
for (element in intArray){
println(element)
}
}
Kotlin not only declares an array of a size of 5, but it also initializes the array with a value passed to the lambda expression. The lambda expression takes one parameter, which means that the expression can be represented using the it keyword:
val doubleArray = DoubleArray(5) { it.toDouble() }
for (element in doubleArray){
println(element)}
}
We can also create our own function to pass to the lambda expression. Create a function that takes one integer parameter and returns an integer:
fun func(i : Int) : Int{
return i * i
}
fun arrayWithLambda(){
val arr = IntArray(5){func(it)}
for (element in arr){
println(element)
}
}
The elements will start from 0 and will increase on every iteration. The func function will return the square of each element. An array of size 5 is initialized with the values 0, 1, 4, 9, and 16.