Bird
0
0

Find the issue in this Kotlin code: val list: MutableList = mutableListOf("a", "b") list.add(null) list.forEach { println(it.length) }

medium📝 Debug Q7 of 15
Kotlin - Null Safety
Find the issue in this Kotlin code: val list: MutableList = mutableListOf("a", "b") list.add(null) list.forEach { println(it.length) }
ACalling length on a nullable String without safe call causes a runtime exception.
BCannot add null to MutableList<String?>.
CMutableList cannot be iterated with forEach.
DNo issues; code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Understand list type and null addition

    The list allows nulls because element type is String?. Adding null is valid.
  2. Step 2: Analyze forEach usage

    Inside forEach, it.length is called without safe call operator. Since it can be null, this causes a runtime NullPointerException.
  3. Final Answer:

    Calling length on a nullable String without safe call causes a runtime exception. -> Option A
  4. Quick Check:

    Nullable elements require safe calls to avoid exceptions [OK]
Quick Trick: Use ?.length for nullable strings to avoid exceptions [OK]
Common Mistakes:
MISTAKES
  • Assuming adding null is invalid
  • Thinking forEach cannot iterate MutableList
  • Ignoring null safety when accessing properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes