Bird
0
0

What is the issue with this Kotlin function?

medium📝 Debug Q7 of 15
Kotlin - Variables and Type System
What is the issue with this Kotlin function?
fun displayLength(obj: Any) {
    if (obj is String) {
        println(obj.length)
    } else {
        println(obj.length)
    }
}
AFunction should return an Int instead of printing
BMissing semicolon after println statements
CIncorrect use of 'is' operator syntax
DAccessing 'length' on 'obj' in else block without confirming it's a String
Step-by-Step Solution
Solution:
  1. Step 1: Review type checking

    The is operator confirms obj is a String only in the if block.
  2. Step 2: Identify problem in else block

    In else, obj might not be a String, so accessing length causes error.
  3. Final Answer:

    Accessing 'length' on 'obj' in else block without confirming it's a String -> Option D
  4. Quick Check:

    Only access String properties after confirming type [OK]
Quick Trick: Check type before accessing properties [OK]
Common Mistakes:
MISTAKES
  • Assuming type after else without check
  • Confusing syntax errors with logical errors
  • Ignoring Kotlin's smart cast rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes