0
0
Kotlinprogramming~5 mins

Accessing elements safely in Kotlin

Choose your learning style9 modes available
Introduction

Sometimes, when you get an item from a list or map, it might not be there. Accessing elements safely helps you avoid errors by checking first.

When you want to get a value from a map but aren't sure if the key exists.
When you want to get an item from a list but the index might be out of range.
When you want to avoid your program crashing due to missing elements.
When you want to provide a default value if the element is not found.
Syntax
Kotlin
val value = map[key] ?: defaultValue
val item = list.getOrNull(index) ?: defaultValue

The ?: operator is called the Elvis operator and provides a default if the left side is null.

getOrNull(index) returns the element at the index or null if the index is invalid.

Examples
Try to get key "c" from the map. Since it doesn't exist, print 0 instead.
Kotlin
val map = mapOf("a" to 1, "b" to 2)
val value = map["c"] ?: 0
println(value)
Try to get the 6th item (index 5). It's out of range, so print -1.
Kotlin
val list = listOf(10, 20, 30)
val item = list.getOrNull(5) ?: -1
println(item)
Get value for key "x" which exists, so print 100.
Kotlin
val map = mapOf("x" to 100)
val value = map["x"] ?: 0
println(value)
Sample Program

This program tries to get a fruit at index 3, which doesn't exist, so it prints "unknown". It also gets scores for Alice and Charlie. Alice's score exists, Charlie's does not, so it prints 0 for Charlie.

Kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    val fruit = fruits.getOrNull(3) ?: "unknown"
    println("Fruit at index 3: $fruit")

    val scores = mapOf("Alice" to 90, "Bob" to 85)
    val aliceScore = scores["Alice"] ?: 0
    val charlieScore = scores["Charlie"] ?: 0
    println("Alice's score: $aliceScore")
    println("Charlie's score: $charlieScore")
}
OutputSuccess
Important Notes

Using safe access avoids crashes from missing elements.

The Elvis operator ?: is very handy for providing fallback values.

getOrNull() works well with lists to avoid index errors.

Summary

Access elements safely to avoid errors when items might be missing.

Use map[key] ?: default to get values with a fallback.

Use list.getOrNull(index) ?: default to safely get list items.