Recall & Review
beginner
What is a
when expression in Kotlin?A
when expression in Kotlin is a powerful alternative to the traditional switch statement. It allows you to check a value against multiple conditions and execute code based on the first matching condition.Click to reveal answer
intermediate
How does
when differ from a traditional switch?Unlike
switch, when can handle any type, not just primitives or enums. It can also check complex conditions, ranges, and even arbitrary expressions.Click to reveal answer
beginner
Can
when be used as an expression that returns a value?Yes!
when is an expression, so it returns a value. You can assign the result of a when expression directly to a variable.Click to reveal answer
intermediate
What happens if no
when branch matches and there is no else branch?If no branch matches and there is no
else branch, the code will not compile. Kotlin requires when expressions to be exhaustive or have an else branch.Click to reveal answer
beginner
Show a simple example of
when used as a switch for integers.Example:<br>
val x = 3
val result = when (x) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown"
}Click to reveal answer
What keyword is used in Kotlin as a powerful alternative to
switch?✗ Incorrect
The
when keyword is Kotlin's powerful alternative to switch.Can
when in Kotlin check for ranges like 1..5?✗ Incorrect
when supports checking ranges, e.g., in 1..5.What must you include in a
when expression to handle unmatched cases?✗ Incorrect
The
else branch handles unmatched cases in when.Is
when in Kotlin a statement or an expression?✗ Incorrect
when can be used as both a statement and an expression.Which of these can
when NOT match against?✗ Incorrect
when cannot match function definitions.Explain how the
when expression in Kotlin works and why it is more powerful than a traditional switch.Think about what makes <code>when</code> flexible and expressive.
You got /5 concepts.
Write a Kotlin
when expression that returns a string describing if a number is positive, negative, or zero.Use simple comparisons inside <code>when</code> branches.
You got /4 concepts.