Bird
0
0

Find the error in this Kotlin code snippet:

medium📝 Debug Q6 of 15
Kotlin - Variables and Type System
Find the error in this Kotlin code snippet:
fun check(x: Any) {
    if (x is Int) {
        println(x + 10)
    } else if (x is String) {
        println(x.length)
    }
}
AMissing else branch
BCannot use <code>+</code> with <code>x</code> without casting
CNo error, code is correct
DCannot access <code>length</code> without explicit cast
Step-by-Step Solution
Solution:
  1. Step 1: Check smart cast usage

    After is Int check, x is smart cast to Int, so x + 10 is valid.
  2. Step 2: Check smart cast for String

    After is String check, x.length is valid without explicit cast.
  3. Final Answer:

    No error, code is correct -> Option C
  4. Quick Check:

    Smart casts allow direct usage = D [OK]
Quick Trick: Kotlin smart casts remove need for explicit casts [OK]
Common Mistakes:
MISTAKES
  • Thinking explicit cast needed
  • Expecting error on operators
  • Ignoring smart cast feature

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes