Accessing Elements: get, first, last, getOrNull
Retrieve elements using index-based and functional accessors.
Many Ways to Access
Kotlin gives you several ways to read elements: by index ([], get), by position (first, last), and safely (getOrNull, firstOrNull).
Index Access with []
The bracket syntax is shorthand for get(index). Throws IndexOutOfBoundsException if the index is invalid.
fun main() {
val items = listOf("a", "b", "c")
println(items[0]) // a
println(items[2]) // c
}All lessons in this course
- listOf, setOf, mapOf: Read-Only Collections
- mutableListOf, mutableMapOf: Mutable Builders
- Accessing Elements: get, first, last, getOrNull
- Iterating and Transforming Collections with Standard Library