Bird
0
0

What will this Kotlin code print?

medium📝 Predict Output Q5 of 15
Kotlin - Control Flow as Expressions
What will this Kotlin code print?
val result = when (2) {
  1 -> "One"
  2 -> "Two"
  else -> "Other"
}
println(result)
ATwo
BCompilation error
COther
DOne
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate the when expression

    Input is 2, so the branch 2 -> "Two" matches.
  2. Step 2: Print the matched branch value

    Variable result is assigned "Two", so println(result) outputs Two.
  3. Final Answer:

    Two -> Option A
  4. Quick Check:

    when expression matches 2 = D [OK]
Quick Trick: when returns matched branch value [OK]
Common Mistakes:
MISTAKES
  • Ignoring else branch
  • Confusing when with switch syntax
  • Expecting numeric output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes