Bird
0
0

What is wrong with this Kotlin code and how can it be fixed?

medium📝 Debug Q6 of 15
Kotlin - Collections Fundamentals

What is wrong with this Kotlin code and how can it be fixed?

val numbers = listOf(5, 10, 15)
val result = numbers[4] ?: 0
println(result)
ANo error; code prints 0
BThe Elvis operator is misplaced; use ?: after println
CThe list is immutable; use a mutable list instead
DIndexOutOfBoundsException occurs; use getOrNull(4) ?: 0 instead
Step-by-Step Solution
Solution:
  1. Step 1: Identify the error

    Accessing numbers[4] throws IndexOutOfBoundsException because index 4 is out of range.
  2. Step 2: Correct safe access

    Use numbers.getOrNull(4) ?: 0 to safely get null if index is invalid, then default to 0.
  3. Final Answer:

    IndexOutOfBoundsException occurs; use getOrNull(4) ?: 0 instead -> Option D
  4. Quick Check:

    Index operator throws exception if out of bounds [OK]
Quick Trick: Use getOrNull() to avoid index exceptions [OK]
Common Mistakes:
MISTAKES
  • Using index operator with ?: expecting no exception
  • Misplacing Elvis operator
  • Confusing mutable and immutable lists

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes