Arrays in Kotlin are able to store multiple values of different data types. Of course if we want we can restrict the arrays to hold the values of a particular data types. In this guide, we will discuss about arrays in Kotlin.
Kotlin Array Declaration
Array that holds multiple different data types.
var arr = arrayOf(10, "BeginnersBook", 10.99, 'A')
Array that can only hold integers
var arr = arrayOf<Int>(1, 22, 55)
Array that can only hold strings
var arr2 = arrayOf<String>("ab", "bc", "cd")
Access Array elements in Kotlin
In the following example, we have an array arr
that has multiple elements of different data types, we are displaying the 4th element of the array using the index (arr[3]
). Since array is mutable, we can change the value of an element, which we have shown in the example below.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ /** * Array that holds multiple different data types */ var arr = arrayOf(10, "BeginnersBook", 10.99, 'A') /** * Displaying 4th element */ println(arr[3]) /** * modifying 4th element */ arr[3] = 100 /** * Displaying 4th element again */ println(arr[3]) }
Output:
Kotlin Array set() and get() functions
get()
In the above example we have used the following statement to access the value of 4th element of the array.
arr[3]
We can rewrite the same statement using get function like this:
arr.get(3)
set()
In the above example we have used the following statement to modify the value of 4th element in the array.
arr[3] = 100
We can rewrite the same statement using set() function like this:
arr.set(3,100)
Size of an array
We can easily find out the size of an array like this:
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var arr = arrayOf(1, 2, 3, 4, 5) println("Size of Array arr is: ${arr.size}") }
Output:
Size of Array arr is: 5
Check the element in an array
We can also check whether an element exists in array or not using the contains().
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var arr = arrayOf(1, 22, "CPS") println("Array contains CPS: ${arr.contains("CPS")}") }
Output:
Kotlin Array first() and last() functions
We can easily find out the first and last element of an array using first() and last() function.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var arr = arrayOf(1, 22, "CPS") println("First Element: ${arr.first()}") println("Last Element: ${arr.last()}") }
Output:
First Element: 1 Last Element: CPS
Finding the index of an element in an array
We can find out the index of a particular element in an array using indexOf() function.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var arr = arrayOf(1, 22, "CPS") println("Index of 22: ${arr.indexOf(22)}") }
Output:
Index of 22: 1
Leave a Reply