Kotlin Array - <init> Constructor



The Kotlin array init constructor is used to creates a new array with the specified size, where each elements is calculated by calling the specified init function.

This init constructor initializes an array and accepts a function that sequentially returns a value to be assigned as the elements of the array.

Syntax

Following is the syntax of Kotlin array init constructor −

<init>(size: Int, init: (Int) -> T)

Parameters

This constructor accepts the following parameters −

  • size: It represents the number of elements the array must contain.

  • init: It represents a function that assigns each element of an array and value returned by this function.

Return value

This constructor returns an instance of an array object.

Example 1

The following is a basic example, we create an array of size 5 using the Kotlin Array classs constructor. The init function assigns the values of the array as 1 and then prints the values in the array −

fun main(args: Array<String>) {
   var array = Array(5) { init -> 1 }
   val len = array.size
   println("The number of elements in the array is: $len")
   println("The elements in the array are: ")
   for (i in 0 until len)
   {
      println(array[i])
   }
}

Output

The above code generate following output −

The number of elements in the array is: 5
The elements in the array are: 
1
1
1
1
1

Example 2

The following example creates an array of size 5, where each element is initialized to twice of its index −

fun main() {
   // Each element is initialized to twice of its index
   val array = Array(5) { index -> index * 2 }

   // Print the contents of the array
   println("Array contents: ${array.joinToString()}")
}

Output

Following is the output −

Array contents: 0, 2, 4, 6, 8

Example 3

Lets create an array of size 10. We then use the init function to assigns the values of the array as the index of the value itself −

fun main(args: Array<String>) {
   // i for initialization
   var array = Array(10) { i -> i }
   val len = array.size
   println("The number of elements in the array is: $len")
   println("The elements in the array are: ")
   for (i in 0 until len)
   {
      println(array[i])
   }
}

Output

Following is the output −

The number of elements in the array is: 10
The elements in the array are: 
0
1
2
3
4
5
6
7
8
9

Example 4

The below example create an array of size 2 and then initialize the string to the each elements −

fun main(args: Array<String>) {
   var array = Array(2) { init -> "Sample String" }
   val len = array.size
   println("The number of elements in the array is: $len")
   println("The elements in the array are: ")
   for (i in 0 until len)
   {
      println(array[i])
   }
}

Output

Following is the output −

The number of elements in the array is: 2
The elements in the array are: 
Sample String
Sample String
kotlin_arrays.htm
Advertisements