0Pricing
Kotlin Academy · Lesson

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

  1. listOf, setOf, mapOf: Read-Only Collections
  2. mutableListOf, mutableMapOf: Mutable Builders
  3. Accessing Elements: get, first, last, getOrNull
  4. Iterating and Transforming Collections with Standard Library
← Back to Kotlin Academy