Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q14 of 15
Kotlin - Null Safety
Identify the error in this Kotlin code snippet:
val list: List = listOf(1, 2, null, 4)
AThe list declaration syntax is incorrect.
BThe list cannot contain <code>null</code> because <code>Int</code> is non-nullable.
CThe <code>listOf</code> function cannot be used with integers.
DThere is no error; the code compiles fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check element type and values

    The list is declared as List<Int>, which means elements cannot be null.
  2. Step 2: Identify the presence of null

    The list contains a null value, which is not allowed for non-nullable types, causing a compilation error.
  3. Final Answer:

    The list cannot contain null because Int is non-nullable. -> Option B
  4. Quick Check:

    Non-nullable list disallows null elements [OK]
Quick Trick: Non-nullable types disallow null values in collections [OK]
Common Mistakes:
MISTAKES
  • Assuming null is allowed in List
  • Thinking listOf syntax is wrong
  • Ignoring Kotlin's null safety rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes