Bird
0
0

Consider this Kotlin code: val list: MutableList = mutableListOf("a", "b", "c") list.add(null) println(list.size) What happens when you run it?

medium📝 Predict Output Q5 of 15
Kotlin - Null Safety
Consider this Kotlin code: val list: MutableList = mutableListOf("a", "b", "c") list.add(null) println(list.size) What happens when you run it?
ACompilation error due to adding null to non-nullable list
BPrints 4
CRuntime exception when adding null
DPrints 3
Step-by-Step Solution
Solution:
  1. Step 1: Check list type and add operation

    The list is MutableList, which does not allow null elements. Trying to add null is not allowed by the compiler.
  2. Step 2: Understand Kotlin's compile-time null safety

    Kotlin prevents adding null to non-nullable collections at compile time, so this code will not compile.
  3. Final Answer:

    Compilation error due to adding null to non-nullable list -> Option A
  4. Quick Check:

    Adding null to non-nullable list = compile error [OK]
Quick Trick: Cannot add null to non-nullable collection types [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime exception instead of compile error
  • Assuming null is added silently
  • Thinking size prints 4 despite error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes