Coding Friction

Kotlin Array

Array is a collection of similar data types such as an Int, String etc. It is used to organize data so sorted and searched can be easily done.

Arrays are mutable and fixed size, they are stored in contiguous memory locations.

Create an Array : In Kotlin there are two ways to create an array

1. Using the arrayOf() function –

val x = arrayOf(1, 2, 3, 4)   //implicit type declaration
val y = arrayOf<Int>(1, 2, 3) //explicit type declaration
val names = arrayOf<String>("Josh", "Sanjay", "justin")

Kotlin has some built-in factory methods to create an array of primitive data types such as :

arrayOf()
intArrayOf()
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()

var arr1: IntArray = intArrayOf(1,2,3,4,5)  
var arr2: BooleanArray = booleanArrayOf(true,false,true)

2. Using the Array constructor The constructor takes two parameter first size of array and second function which accepts the index of a given element and returns the initial value of that element.

Syntax :

Array(size: Int, init: (Int) -> T)  
val num = Array(5, {i-> i*1})

Example :

fun main()
{
    val arr = Array(3, { i -> i * 1 })
    for (i in 0..arr.size-1)
    {
        println(arr[i])
    }
}

Output

0
1
2

Initialize an array of size with default value : –

we can initialize an array of size 3 with default value, example

fun main(args: Array<String>){  
var myArray = Array<Int>(3){12}  
  
    for(x in myArray){  
        println(x)  
    }  
} 

Output

12
12
12
12
12

Modify and access elements of array : –

Kotlin provides a set() function to modify an array and access the element of the array. You can also modify an array by assigning elements at array index.

set() function example :

fun main(args: Array<String>) {
    val arr1 = arrayOf(1,2,3,4)  
    val arr2 = arrayOf<Int>(100,101,102,103)
    arr1.set(0,9)
    arr1[1] = 90 //assigning element at array index
    for(element in arr1){  
        println(element)  
    } 
}

Output

9
90
3
4

get() function example :

fun main(args: Array<String>) {  
 val arr1 = arrayOf(1,2,3,4)  
 val arr2 = arrayOf<Int>(100,101,102,103)  
println(arr1.get(3))  
println(arr1[2]) // get element by index 
// println(arr1[4]) // java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
  
}

Output

4
3

when we try get or set an element at index position greater than array size then it will throw an ArrayIndexOutOfBoundsException.

Traverse an array using range function : –

Kotlin array elements are also traversed by index range function , range(minVal..maxVal) or range(maxVal..minVal).

fun main(args: Array<String>){  
var arr = intArrayOf(2,4,6,8,10)    
    for (index in 0..arr.size-1){  
        println(arr[index])  
    }  
}  

Output

2
4
6
8
10

Leave a Comment

Your email address will not be published. Required fields are marked *