Recall & Review
beginner
What is a
when expression in Kotlin?A
when expression in Kotlin is a control structure that checks a value against multiple conditions and returns a result based on the first matching condition.Click to reveal answer
beginner
How do you use
when as an expression to return a value?You assign the
when expression to a variable. Each branch returns a value, and the whole when expression evaluates to that value.Click to reveal answer
intermediate
What happens if no branch matches in a
when expression used as a value?If no branch matches, and there is no
else branch, the code will not compile. You must provide an else branch to cover all cases.Click to reveal answer
intermediate
Can
when expression branches return different types?No. All branches must return values of the same type or compatible types so the
when expression has a consistent return type.Click to reveal answer
beginner
Example: What is the value of
result after this code?<br>val x = 2
val result = when (x) {
1 -> "One"
2 -> "Two"
else -> "Other"
}The value of
result is "Two" because the when expression matches the case 2 and returns "Two".Click to reveal answer
What must a
when expression used as a value always include?✗ Incorrect
When used as an expression,
when must cover all cases, usually by including an else branch.What type of value does a
when expression return?✗ Incorrect
The
when expression returns a value whose type matches all branch results.What happens if you omit the
else branch in a when expression used as a value?✗ Incorrect
Without an
else branch, the compiler cannot guarantee all cases are covered, so it does not compile.Which of these is a valid way to assign a value using
when expression?✗ Incorrect
The correct syntax uses arrows (->) and includes an else branch to cover all cases.
Can a
when expression be used without an argument?✗ Incorrect
A
when expression can be used without an argument to check conditions directly in branches.Explain how a
when expression returns a value in Kotlin and why the else branch is important.Think about how the program decides what value to give back.
You got /4 concepts.
Describe the rules for the types of values returned by each branch in a
when expression used as a value.Consider what happens if branches return different kinds of values.
You got /4 concepts.