How do I access elements safely in Kotlin collections?

In Kotlin, you can access collection elements safely by using functions that return null instead of throwing exceptions when an index/key is missing.

Lists / arrays: use getOrNull

val items = listOf("A", "B", "C")

val first = items.getOrNull(0)   // "A"
val missing = items.getOrNull(10) // null

This is safer than:

val missing = items[10] // Throws IndexOutOfBoundsException

You can combine it with the Elvis operator:

val value = items.getOrNull(10) ?: "Default value"

Lists / arrays: use getOrElse

If you want a fallback value:

val items = listOf("A", "B", "C")

val value = items.getOrElse(10) { index ->
    "No item at index $index"
}

First / last elements safely

Instead of first() or last(), which throw if the collection is empty, use:

val items = emptyList<String>()

val first = items.firstOrNull()
val last = items.lastOrNull()

With a predicate:

val numbers = listOf(1, 2, 3, 4)

val firstEven = numbers.firstOrNull { it % 2 == 0 } // 2
val firstBig = numbers.firstOrNull { it > 10 }      // null

Single element safely

Use singleOrNull() when you expect exactly one matching element:

val users = listOf("Alice", "Bob")

val onlyAlice = users.singleOrNull { it == "Alice" } // "Alice"
val onlyZoe = users.singleOrNull { it == "Zoe" }     // null

Note: singleOrNull() also returns null if there is more than one match.

Maps: safe access by key

Map access already returns nullable values:

val ages = mapOf("Alice" to 30)

val aliceAge = ages["Alice"] // 30
val bobAge = ages["Bob"]     // null

Use a default if needed:

val bobAge = ages["Bob"] ?: 0

Or use getOrDefault:

val bobAge = ages.getOrDefault("Bob", 0)

Check bounds manually if needed

val items = listOf("A", "B", "C")
val index = 2

if (index in items.indices) {
    println(items[index])
}

Summary

Prefer these safe APIs:

list.getOrNull(index)
list.getOrElse(index) { default }
list.firstOrNull()
list.lastOrNull()
list.singleOrNull()
map[key] ?: default
map.getOrDefault(key, default)

Use direct indexing like list[index] only when you are certain the index is valid.