Careeroza
Accessing and Changing Elements
Index Access
Example
Use [index] to read or write. Indexes start at 0, and the last index is size - 1.
fun main() {
val scores = arrayOf(72, 88, 95, 60)
println(scores[0])
println(scores[scores.size - 1])
println(scores.last())
scores[3] = 65 // the array is val, but its elements can change
println(scores.contentToString())
println(scores.getOrNull(10)) // safe access
println(scores.getOrElse(10) { -1 })
}Output
72 60 60 [72, 88, 95, 65] null -1
Index Out of Bounds
Crash
Reading outside the array throws ArrayIndexOutOfBoundsException.
fun main() {
val days = arrayOf("Mon", "Tue", "Wed")
println(days[2])
println(days[3])
}Output
Wed Exception: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Looping Over an Array
Example
Loop over the values, the indices, or both.
fun main() {
val steps = arrayOf(4200, 8100, 10500, 6700)
for (s in steps) print("$s ")
println()
for (i in steps.indices) println("Day ${i + 1}: ${steps[i]}")
for ((i, s) in steps.withIndex()) if (s >= 10_000) println("Goal reached on day ${i + 1}")
}Output
4200 8100 10500 6700 Day 1: 4200 Day 2: 8100 Day 3: 10500 Day 4: 6700 Goal reached on day 3