Bird
0
0

You want to assign a descriptive string to a variable based on an integer code using when as an expression. Which code correctly handles codes 1, 2, and any other code as "Unknown"?

hard📝 Application Q8 of 15
Kotlin - Control Flow as Expressions
You want to assign a descriptive string to a variable based on an integer code using when as an expression. Which code correctly handles codes 1, 2, and any other code as "Unknown"?
Aval desc = when { code == 1 -> "Start" code == 2 -> "Stop" else -> "Unknown" }
Bval desc = when { code == 1 -> "Start" code == 2 -> "Stop" else "Unknown" }
Cval desc = when code { 1 -> "Start" 2 -> "Stop" else -> "Unknown" }
Dval desc = when (code) { 1: "Start" 2: "Stop" else: "Unknown" }
Step-by-Step Solution
Solution:
  1. Step 1: Check syntax for when with conditions

    val desc = when { code == 1 -> "Start" code == 2 -> "Stop" else -> "Unknown" } correctly uses when without argument and conditions with arrows, including else branch.
  2. Step 2: Identify errors in other options

    val desc = when code { 1 -> "Start" 2 -> "Stop" else -> "Unknown" }: missing parentheses around the argument (when code { ... }); val desc = when { code == 1 -> "Start" code == 2 -> "Stop" else "Unknown" }: missing arrow in the else branch (else "Unknown"); val desc = when (code) { 1: "Start" 2: "Stop" else: "Unknown" }: uses colons instead of arrows (->).
  3. Final Answer:

    val desc = when { code == 1 -> "Start" code == 2 -> "Stop" else -> "Unknown" } -> Option A
  4. Quick Check:

    when with conditions needs arrows and else branch [OK]
Quick Trick: Use arrows and else branch for all when expressions [OK]
Common Mistakes:
MISTAKES
  • Missing arrow in else branch
  • Using colons instead of arrows
  • Omitting else branch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes