Kotlin Academy · Lesson

Accessing Elements: get, first, last, getOrNull

Retrieve elements using index-based and functional accessors.

Lesson 3 of 413 steps

Accessing Elements: get, first, last, getOrNull is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

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.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

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

Yes — any 3 lessons of the Kotlin Academy learning path, including “Accessing Elements: get, first, last, getOrNull”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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