In Learning Kotlin – Part 1 we looked at some basic concepts like type inference and string handling. In this part we deal with arrays:
You can easily create an array with the arrayOf function
var myArray = arrayOf(1, 1.23, "Jörn")
Element access
You can access arrays directly with the [] operator
println(myArray[2]) myArray[1] = 3.14
For the first respective last element you have the convenience functions first() and last()
println("First: ${myArray.first()}") println("Last: ${myArray.last()}")
If You want to find out if a specific elements is in an array you use the contains method
println("Jörn in array: ${myArray.contains("Jörn")}")
To get its position in the array you can use the indexOf
println("Index of Jörn: ${myArray.indexOf("Jörn")}")
If the element is not found the return value is -1
Array size
The size of an array can be determined with the size property
println("Array length: ${myArray.size}")
Slicing
To create a new array with a subset of the data of the old array the copyOfRange method comes in handy:
var partArray = myArray.copyOfRange(0,1)