Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q5 of 15
Kotlin - Data Types
What will be the output of this Kotlin code?
fun printAny(value: Any) {
    when(value) {
        is String -> println("String: $value")
        is Int -> println("Int: $value")
        else -> println("Unknown type")
    }
}

printAny(10)
printAny("hello")
printAny(3.14)
AInt: 10 Unknown type String: hello
BUnknown type Unknown type Unknown type
CCompilation error
DInt: 10 String: hello Unknown type
Step-by-Step Solution
Solution:
  1. Step 1: Analyze when expression branches

    The function checks if value is String, Int, or else.
  2. Step 2: Check each call

    printAny(10) matches Int branch, prints "Int: 10". printAny("hello") matches String branch, prints "String: hello". printAny(3.14) matches else branch, prints "Unknown type".
  3. Final Answer:

    Int: 10 String: hello Unknown type -> Option D
  4. Quick Check:

    Type checks with when = correct output [OK]
Quick Trick: Use when with is to check Any type at runtime [OK]
Common Mistakes:
MISTAKES
  • Mixing order of outputs
  • Expecting 3.14 to match Int or String
  • Assuming compilation error due to when

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes