Bird
0
0

Identify the error in this Kotlin code snippet and fix it:

medium📝 Debug Q14 of 15
Kotlin - Null Safety

Identify the error in this Kotlin code snippet and fix it:

val obj: Any = "Hello"
val num: Int = obj as? Int
println(num)
AReplace <code>as?</code> with <code>as</code>
BChange <code>val num: Int</code> to <code>val num: Int?</code>
CCast <code>obj</code> to <code>String</code> instead of <code>Int</code>
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable types and cast

    The safe cast obj as? Int returns null if cast fails, so the result is nullable Int?.
  2. Step 2: Fix type mismatch

    Declaring num as non-nullable Int causes a type mismatch error. Changing it to Int? fixes this.
  3. Final Answer:

    Change val num: Int to val num: Int? -> Option B
  4. Quick Check:

    Safe cast returns nullable type [OK]
Quick Trick: Safe cast result must be nullable type [OK]
Common Mistakes:
MISTAKES
  • Using non-nullable type for safe cast result
  • Replacing safe cast with forced cast causing exceptions
  • Ignoring type mismatch errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes