Bird
0
0

Which of the following Kotlin snippets correctly uses when as an expression to assign a value to val result?

easy📝 Conceptual Q2 of 15
Kotlin - Control Flow as Expressions
Which of the following Kotlin snippets correctly uses when as an expression to assign a value to val result?
Aval result = when { num == 1 -> "One" num == 2 -> "Two" }
Bval result = when (num) { 1 -> "One"; 2 -> "Two"; else -> "Other" }
Cval result = when (num) { 1 -> "One" 2 -> "Two" }
Dval result = when (num) { 1 -> "One"; 2 -> "Two" } else "Other"
Step-by-Step Solution
Solution:
  1. Step 1: Check syntax for when expression

    Each branch should be separated by commas or new lines, and an else branch is required if not all cases are covered.
  2. Step 2: Validate options

    val result = when (num) { 1 -> "One"; 2 -> "Two"; else -> "Other" } uses correct syntax with else and proper arrow notation.
  3. Final Answer:

    val result = when (num) { 1 -> "One"; 2 -> "Two"; else -> "Other" } is syntactically correct.
  4. Quick Check:

    Look for else and proper arrow usage [OK]
Quick Trick: Use arrows and else branch for complete when expression [OK]
Common Mistakes:
MISTAKES
  • Missing else branch causing compilation error
  • Using semicolons incorrectly
  • Incorrect arrow usage or missing arrows

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes