Array is collection of similar data types either of Int, String etc. Array in Kotlinis mutable in nature with fixed size which means we can perform both read and write operations on elements of array.
Constructor of array:
Array constructor is declared with specified size and init function. The init function is used to returns the elements of array with their index.
Kotlin Array can be created using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf() functions.
Kotlin array declaration - using arrayOf() function
Kotlin array declaration - using intArrayOf() function
Modify and access elements of array
Kotlin has set() and get() functions that can direct modify and access the particular element of array respectively.
The set() function is used to set element at particular index location. This is also done with assigning element at array index. Array get() function is used to get element from specified index.
Kotlin array set() function example
5 2 6 4 11 12 10 8
Kotlin array get() function example
1 3 13 14
Kotlin Array Example 1:
In this example, we are simply initialize an array of size 5 with default value as 0 and traverse its elements. The index value of array starts from 0. First element of array is placed at index value 0 and last element at one less than the size of array.
0 0 0 0 0
Kotlin Array Example 2:
We can also rewrite the value of array using its index value. Since, we can able to modify the value of array, so array is called as mutable property.
0 10 0 15 0
Kotlin Array Example 3 - using arrayOf() and intArrayOf() function:
Array in Kotlin can also be declared using library functions such as arrayOf(), intArrayOf(), etc. Let's see the example of array using arrayOf() and intArrayOf() function.
Ajay Prakesh Michel John Sumit 1 10 4 6 15 5 10 20 12 15 1 10 4 Ajay Prakesh 5 10 15 20 25
Kotlin Array Example 4
Suppose when we try to insert an element at index position greater than array size then what will happen?
It will throw an ArrayIndexOutOfBoundException. This is because the index value is not present at which we tried to insert element. Due to this, array is called fixed size length. For example:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at ArrayListKt.main(Array.kt:4)
Kotlin Array Example 5 - traversing using range:
The Kotlin's array elements are also traversed using index range (minValue..maxValue) or (maxValue..minValue). Let's see an example of array traversing using range.
5 10 20 12 15 5 10 20 12 15