Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q6 of 15
Kotlin - Null Safety

Identify the error in this Kotlin code snippet:

val obj: Any = 10
val str: String = obj as? String
println(str)
AMissing explicit type declaration for obj
BSafe cast operator is used incorrectly
CCannot assign nullable type to non-nullable variable
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable types and cast

    The safe cast as? returns a nullable type, but str is declared non-nullable String.
  2. Step 2: Identify type mismatch error

    Assigning nullable result to non-nullable variable causes a compilation error.
  3. Final Answer:

    Cannot assign nullable type to non-nullable variable -> Option C
  4. Quick Check:

    Safe cast returns nullable, must assign to nullable variable = A [OK]
Quick Trick: Safe cast returns nullable; assign to nullable variable [OK]
Common Mistakes:
MISTAKES
  • Assigning safe cast result to non-nullable variable
  • Ignoring nullable type returned by safe cast
  • Confusing safe cast with unsafe cast

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes