0Pricing
Kotlin Academy · Lesson

Accessing Elements: get, first, last, getOrNull

Retrieve elements using index-based and functional accessors.

Accessing Elements: get, first, last, getOrNull is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
}

get vs []

list.get(i) is identical to list[i] — different syntax, same behavior.

fun main() {
    val items = listOf(10, 20, 30)
    println(items.get(1)) // 20
    println(items[1])     // 20
}

getOrNull for Safe Access

getOrNull(i) returns null instead of throwing if the index is out of range.

fun main() {
    val items = listOf("x", "y")
    println(items.getOrNull(0)) // x
    println(items.getOrNull(5)) // null
}

getOrElse with a Default

getOrElse(i) { default } computes a default value lazily if the index is invalid.

fun main() {
    val items = listOf(1, 2, 3)
    println(items.getOrElse(10) { -1 }) // -1
    println(items.getOrElse(1) { -1 })  // 2
}

first and last

first() and last() return the corresponding elements; both throw if the list is empty.

fun main() {
    val nums = listOf(5, 8, 12)
    println(nums.first()) // 5
    println(nums.last())  // 12
}

firstOrNull / lastOrNull

The ...OrNull variants return null instead of throwing on empty lists — much safer.

fun main() {
    val empty: List<Int> = emptyList()
    println(empty.firstOrNull()) // null
    println(empty.lastOrNull())  // null
}

Predicate Versions

first { predicate } returns the first matching element; find { predicate } is the nullable alias for firstOrNull { predicate }.

fun main() {
    val nums = listOf(3, 7, 8, 11)
    println(nums.first { it > 5 })       // 7
    println(nums.firstOrNull { it > 100 }) // null
    println(nums.find { it > 100 })       // null (same)
}

Accessing Map Values

Maps use the same [] syntax, but it returns nullable. getValue(key) throws if the key is missing; getOrDefault provides a fallback.

fun main() {
    val ages = mapOf("Alice" to 30, "Bob" to 25)
    println(ages["Alice"])             // 30
    println(ages["Charlie"])           // null
    println(ages.getOrDefault("Z", 0)) // 0
}

elementAt and elementAtOrNull

Sets and other collections without index support also provide elementAt(i) and its OrNull variant.

fun main() {
    val s = setOf("a", "b", "c")
    println(s.elementAt(1))          // b
    println(s.elementAtOrNull(10))   // null
}

Picking the Right Accessor

Prefer the safe variants (getOrNull, firstOrNull, getOrDefault) unless you can prove the index is valid. The exceptions are expensive and easy to forget to handle.

fun headOf(list: List<Int>): Int? = list.firstOrNull()
fun main() {
    println(headOf(listOf(1, 2, 3))) // 1
    println(headOf(emptyList()))      // null
}

Quick Check

Which accessor returns null instead of throwing when the index is out of range?

Recap

Use []/get for direct access (throws on error). Prefer getOrNull, firstOrNull, lastOrNull, getOrDefault, and getOrElse when bounds may be invalid. Maps use [] for nullable, getValue for throwing.

Frequently asked questions

Is the “Accessing Elements: get, first, last, getOrNull” lesson free?

Yes — the full text of “Accessing Elements: get, first, last, getOrNull” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Accessing Elements: get, first, last, getOrNull”?

Retrieve elements using index-based and functional accessors. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Accessing Elements: get, first, last, getOrNull” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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