Bird
Raised Fist0
Kotlinprogramming~10 mins

Accessing elements safely in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Accessing elements safely
Start
↓
Access element by index
↓
Is index within bounds?
No→Return null or default
Yes↓
Return element
↓
End
This flow shows how Kotlin safely accesses elements by checking if the index is valid before returning the element or null.
Execution Sample
Kotlin
val list = listOf("a", "b", "c")
val element = list.getOrNull(2)
println(element)
This code tries to get the element at index 2 safely and prints it or null if out of bounds.
Execution Table
StepActionIndexIs index valid?ResultOutput
1Define list--["a", "b", "c"]-
2Access element at index2Yes (0 <= 2 < 3)Element = "c"-
3Print element---"c"
4Access element at index5No (5 >= 3)Element = null-
5Print element---null
💡 Index 5 is out of bounds, so getOrNull returns null and stops safely.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
list-["a", "b", "c"]["a", "b", "c"]["a", "b", "c"]
elementnull"c"nullnull
Key Moments - 2 Insights
Why does getOrNull return null instead of crashing when index is out of range?
Because getOrNull checks if the index is valid before accessing. If invalid, it returns null safely instead of throwing an error, as shown in execution_table row 4.
What happens if we use list[index] directly with an invalid index?
Using list[index] with an invalid index throws an exception and crashes the program. getOrNull avoids this by returning null safely, as seen in the flow and execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'element' after step 2?
A"b"
B"c"
Cnull
D"a"
💡 Hint
Check the 'Result' column in execution_table row 2 for the element value.
At which step does the index become invalid and element becomes null?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the 'Is index valid?' column in execution_table rows 2 and 4.
If we change the index in step 2 to 1, what will be the output at step 3?
A"b"
Bnull
C"c"
DException
💡 Hint
Refer to variable_tracker and execution_table to see what element corresponds to index 1.
Concept Snapshot
Access elements safely in Kotlin using getOrNull(index).
Returns element if index is valid, else returns null.
Prevents crashes from invalid index access.
Use safe calls or null checks when using getOrNull.
Example: val e = list.getOrNull(2) ?: "default"
Full Transcript
This lesson shows how to access list elements safely in Kotlin using getOrNull. The code defines a list of three strings and tries to get the element at index 2. Since index 2 is valid, getOrNull returns the element "c". When trying to access index 5, which is invalid, getOrNull returns null instead of crashing. This prevents errors from invalid index access. The variable tracker shows how the element variable changes from null to "c" and back to null. Key moments explain why getOrNull returns null safely and what happens if we use direct indexing with invalid index. The quiz tests understanding of element values at different steps and the behavior when changing the index. Remember to use getOrNull to avoid crashes and handle nulls safely.

Practice

(1/5)
1.

What does the Kotlin expression map[key] ?: "default" do?

easy
A. Removes the key from the map if it exists.
B. Returns the value for key if it exists, otherwise returns "default".
C. Throws an error if key is not in the map.
D. Always returns "default" regardless of key.

Solution

  1. Step 1: Understand map access with []

    Accessing map[key] returns the value if key exists, or null if it doesn't.
  2. Step 2: Use the Elvis operator ?: for fallback

    The expression ?: "default" means if the left side is null, return "default" instead.
  3. Final Answer:

    Returns the value for key if it exists, otherwise returns "default". -> Option B
  4. Quick Check:

    map[key] ?: default = safe access with fallback [OK]
Hint: Use ?: to provide a default when key might be missing [OK]
Common Mistakes:
  • Thinking it throws an error if key is missing
  • Assuming it always returns default
  • Confusing with removing keys
2.

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?

easy
A. myList.getOrNull(2) ?: -1
B. myList[2] ?: -1
C. myList.get(2) ?: -1
D. myList.getOrElse(2, -1)

Solution

  1. Step 1: Understand safe list access methods

    myList.getOrNull(2) returns the element at index 2 or null if out of bounds.
  2. Step 2: Use Elvis operator for default

    ?: -1 returns -1 if getOrNull returns null.
  3. Final Answer:

    myList.getOrNull(2) ?: -1 -> Option A
  4. Quick Check:

    getOrNull + ?: = safe get with fallback [OK]
Hint: Use getOrNull(index) ?: default for safe list access [OK]
Common Mistakes:
  • Using myList[2] which throws exception if index invalid
  • Using get(2) which throws exception if index invalid
  • Confusing getOrElse syntax
3.

What is the output of this Kotlin code?

val map = mapOf("a" to 1, "b" to 2)
println(map["c"] ?: 0)
medium
A. null
B. 2
C. Exception thrown
D. 0

Solution

  1. Step 1: Check map access for key "c"

    Key "c" does not exist in the map, so map["c"] returns null.
  2. Step 2: Apply Elvis operator

    ?: 0 returns 0 because the left side is null.
  3. Final Answer:

    0 -> Option D
  4. Quick Check:

    map[missingKey] ?: default = default [OK]
Hint: Missing keys return null, use ?: for default [OK]
Common Mistakes:
  • Expecting null to print instead of default
  • Thinking exception is thrown
  • Confusing existing key values
4.

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)
medium
A. val value = list.get(5) ?: -1
B. val value = list[5]
C. val value = list.getOrNull(5) ?: -1
D. val value = list.getOrElse(5, -1)

Solution

  1. Step 1: Understand list access with []

    Using list[5] throws an IndexOutOfBoundsException because index 5 is out of range.
  2. Step 2: Use safe access method

    list.getOrNull(5) returns null if index is invalid, so combined with ?: -1 it safely returns -1.
  3. Final Answer:

    val value = list.getOrNull(5) ?: -1 -> Option C
  4. Quick Check:

    Use getOrNull + ?: to avoid exceptions [OK]
Hint: Replace [] with getOrNull + ?: for safe index access [OK]
Common Mistakes:
  • Using [] which throws exception if index invalid
  • Using get(5) which throws exception
  • Confusing getOrElse syntax
5.

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?

hard
A. val total = (scores["Bob"] ?: 0) + (bonuses.getOrNull(2) ?: 0)
B. val total = (scores.getOrNull("Bob") ?: 0) + (bonuses.getOrNull(2) ?: 0)
C. val total = (scores["Bob"] ?: 0) + (bonuses[2] ?: 0)
D. val total = (scores["Bob"] ?: 0) + bonuses.get(2)

Solution

  1. Step 1: Access map value safely

    scores["Bob"] ?: 0 safely gets Bob's score or 0 if missing.
  2. Step 2: Access list element safely

    bonuses.getOrNull(2) ?: 0 safely gets bonus at index 2 or 0 if out of bounds.
  3. Step 3: Sum the two values

    Adding these two safe values gives the total without errors.
  4. Final Answer:

    val total = (scores["Bob"] ?: 0) + (bonuses.getOrNull(2) ?: 0) -> Option A
  5. Quick Check:

    Safe map + safe list access with ?: for default [OK]
Hint: Use ?: with map and getOrNull for list to avoid errors [OK]
Common Mistakes:
  • Using bonuses[2] which throws exception if index invalid
  • Using getOrNull on map which is invalid
  • Not providing default fallback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard