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.
Accessing elements safely in 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.
val map = mapOf("a" to 1, "b" to 2) val value = map["c"] ?: 0 println(value)
val list = listOf(10, 20, 30) val item = list.getOrNull(5) ?: -1 println(item)
val map = mapOf("x" to 100) val value = map["x"] ?: 0 println(value)
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.
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") }
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.
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.
Practice
What does the Kotlin expression map[key] ?: "default" do?
Solution
Step 1: Understand map access with
Accessing[]map[key]returns the value ifkeyexists, ornullif it doesn't.Step 2: Use the Elvis operator
The expression?:for fallback?: "default"means if the left side isnull, return "default" instead.Final Answer:
Returns the value forkeyif it exists, otherwise returns "default". -> Option BQuick Check:
map[key] ?: default = safe access with fallback [OK]
- Thinking it throws an error if key is missing
- Assuming it always returns default
- Confusing with removing keys
Which of the following is the correct Kotlin syntax to safely get the element at index 2 from a list myList, returning -1 if the index is out of bounds?
Solution
Step 1: Understand safe list access methods
myList.getOrNull(2)returns the element at index 2 ornullif out of bounds.Step 2: Use Elvis operator for default
?: -1returns-1ifgetOrNullreturnsnull.Final Answer:
myList.getOrNull(2) ?: -1 -> Option AQuick Check:
getOrNull + ?: = safe get with fallback [OK]
- Using myList[2] which throws exception if index invalid
- Using get(2) which throws exception if index invalid
- Confusing getOrElse syntax
What is the output of this Kotlin code?
val map = mapOf("a" to 1, "b" to 2)
println(map["c"] ?: 0)Solution
Step 1: Check map access for key "c"
Key "c" does not exist in the map, somap["c"]returnsnull.Step 2: Apply Elvis operator
?: 0returns 0 because the left side isnull.Final Answer:
0 -> Option DQuick Check:
map[missingKey] ?: default = default [OK]
- Expecting null to print instead of default
- Thinking exception is thrown
- Confusing existing key values
Identify the error in this Kotlin code snippet and choose the corrected version:
val list = listOf(10, 20, 30) val value = list[5] ?: -1 println(value)
Solution
Step 1: Understand list access with
Using[]list[5]throws anIndexOutOfBoundsExceptionbecause index 5 is out of range.Step 2: Use safe access method
list.getOrNull(5)returnsnullif index is invalid, so combined with?: -1it safely returns-1.Final Answer:
val value = list.getOrNull(5) ?: -1 -> Option CQuick Check:
Use getOrNull + ?: to avoid exceptions [OK]
- Using [] which throws exception if index invalid
- Using get(5) which throws exception
- Confusing getOrElse syntax
You have a map val scores = mapOf("Alice" to 90, "Bob" to 85) and a list val bonuses = listOf(5, 10). You want to safely get Bob's score and the bonus at index 2, returning 0 if missing, then sum them. Which code correctly does this?
Solution
Step 1: Access map value safely
scores["Bob"] ?: 0safely gets Bob's score or 0 if missing.Step 2: Access list element safely
bonuses.getOrNull(2) ?: 0safely gets bonus at index 2 or 0 if out of bounds.Step 3: Sum the two values
Adding these two safe values gives the total without errors.Final Answer:
val total = (scores["Bob"] ?: 0) + (bonuses.getOrNull(2) ?: 0) -> Option AQuick Check:
Safe map + safe list access with ?: for default [OK]
- Using bonuses[2] which throws exception if index invalid
- Using getOrNull on map which is invalid
- Not providing default fallback
Ready to prove it?
Pass the test and this pattern moves unknown
