Bird
0
0

Which of the following is the correct syntax for a when expression returning a value in Kotlin?

easy📝 Syntax Q3 of 15
Kotlin - Control Flow as Expressions
Which of the following is the correct syntax for a when expression returning a value in Kotlin?
Aval output = when(x) { 1 -> "One"; 2 -> "Two"; else -> "Other" }
Bval output = when x { 1 -> "One"; 2 -> "Two"; else -> "Other" }
Cval output = when(x) { 1 : "One"; 2 : "Two"; else : "Other" }
Dval output = when { x == 1 -> "One", x == 2 -> "Two", else -> "Other" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand when with argument syntax

    val output = when(x) { 1 -> "One", 2 -> "Two", else -> "Other" } correctly uses when with argument and arrows.
  2. Step 2: Identify syntax errors in other options

    val output = when x { 1 -> "One"; 2 -> "Two"; else -> "Other" } misses parentheses; val output = when(x) { 1 : "One"; 2 : "Two"; else : "Other" } uses colons instead of arrows; val output = when { x == 1 -> "One", x == 2 -> "Two", else -> "Other" } uses when without argument.
  3. Final Answer:

    val output = when(x) { 1 -> "One"; 2 -> "Two"; else -> "Other" } -> Option A
  4. Quick Check:

    Correct when syntax uses parentheses and arrows [OK]
Quick Trick: Use arrows (->) and parentheses correctly in when with argument [OK]
Common Mistakes:
MISTAKES
  • Missing parentheses after when
  • Using colons instead of arrows
  • Using semicolons incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes