Saturday 2 December 2017

Kotlin: Define array using factory function

Kotlin provides a factory function, which takes size and a function ‘f’ as arguments to define an array. The function ‘f’ is used to provide initial values to the array.

var squares = Array(5, { i -> i * i })
Above statement define an array 'squares' of size 5 and initialize {1, 4, 9, 16, 25}

ArrayFactoryFunction.kt
fun main(args: Array<String>) {

 var squares = Array(5, { i -> i * i })
 var cubes = Array(5, { i -> i * i * i })

 println("Elements in squares array : ")
 for (ele in squares) {
  println(ele)
 }

 println("\nElements in cubes array : ")
 for (ele in cubes) {
  println(ele)
 }

}


Output
Elements in squares array :
0
1
4
9
16

Elements in cubes array :
0
1
8
27
64



Previous                                                 Next                                                 Home

No comments:

Post a Comment