Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Control Flow as Expressions
What will be the output of this Kotlin code?
fun test(obj: Any) {
    when (obj) {
        is String -> println(obj.length)
        is Int -> println(obj + 1)
        else -> println("Unknown")
    }
}

test("Hello")
test(5)
test(3.14)
A5 6 7
B5 6 Unknown
CHello 6 Unknown
D5 5 Unknown
Step-by-Step Solution
Solution:
  1. Step 1: Analyze each call

    For test("Hello"), obj is String, so prints length 5.
    For test(5), obj is Int, so prints 5 + 1 = 6.
    For test(3.14), no matching type, prints "Unknown".
  2. Step 2: Confirm output lines

    Outputs are:
    5
    6
    Unknown
  3. Final Answer:

    5 6 Unknown -> Option B
  4. Quick Check:

    Smart cast uses type to choose output [OK]
Quick Trick: Match type in when to get output [OK]
Common Mistakes:
MISTAKES
  • Confusing string length with string itself
  • Adding 1 to string instead of int
  • Expecting default else to print number

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes