In this article, you will learn what are arrays, how to declare them, how to access and set elements of an array, and other common functions that come very handy when working with arrays in Kotlin.
Arrays
Arrays in kotlin are used to store multiple values of different data types.
fun main(args: Array<String>) {
val text: Array<Any> = arrayOf('c', 'd', 0.9, 1)
val letters: Array<Char> = arrayOf('c' ,'d', 'e')
val numbers: Array<Int> = arrayOf(1, 2, 3, 4)
println(text)
println(letters)
println(numbers)
}
To declare an array, Kotlin provides us with an arrayOf method where we can pass our set of values as an argument. Line 2 represents the array of Any data type, as it consists of Char, Double, and Int inside the same array. Whereas, line 3 is strictly characters and line 4 is strictly integer.
Note that it is not mandatory to specify the arrayOf type as mentioned in line 4. Kotlin’s compiler is powerful enough to infer it. This capability of Kotlin is known as Type inference.
Access an element from an Array
Let’s explore how we can get and set an element of Array.
fun main(args: Array<String>) {
val letters: Array<Char> = arrayOf('c' ,'d', 'e')
println(letters) // prints ['c', 'd', 'e']
letters[0] = 'a'
println(letters) // prints ['a', 'd', 'e']
println(letters[2]) // prints 'e' (element at index 2)
}
Get an element from an Array
To access an element from an Array, we can use the index of an element. The index in an array starts from 0. In the above example, line 6: letters[2] get the element from the index 2 which means the third element from the left.
Set a new value to an element of an array
To set a value to an item of an array we can use the index of that item. In the above example, line 4: letters[0] = ‘a’ sets the element at index 0 to ‘a’.
Some Important in-build methods to work with Arrays
size(): Returns the size of an array in the form of Int.
contains(item): Returns boolean value denoting whether or not the given item is present in the array.
indexOf(item): Returns the index of a given item as an Int.
first(): Returns the first element of an array.
last(): Returns the last element of an array.
fun main(args: Array<String>) {
val letters = arrayOf('c' ,'d', 'e')
println("Size = ${letters.size}") // prints 3
println("Contains 'a' = ${letters.contains('a')}") // prints false
println("Contains 'c' = ${letters.contains('c')}") // prints true
println("IndexOf 'c' = ${letters.indexOf('c')}") // prints 0
println("First element = ${letters.first()}") // prints c
println("Last element = ${letters.last()}") // prints 'e'
}
In the next article, we will learn about Strings.
No responses yet