Recall & Review
beginner
What is the purpose of the
when expression in Kotlin?The
when expression in Kotlin is used to check a value against multiple conditions and execute code based on which condition matches. It is similar to a switch statement in other languages.Click to reveal answer
beginner
How do you check multiple conditions in a single
when branch?You can check multiple conditions by separating them with commas in the same branch. For example:
when(x) { 1, 2, 3 -> println("x is 1, 2, or 3") }.Click to reveal answer
intermediate
Can
when be used without an argument in Kotlin?Yes,
when can be used without an argument to evaluate boolean expressions in each branch. For example: when { x > 0 -> ...; x == 0 -> ... }.Click to reveal answer
intermediate
What happens if none of the
when conditions match and there is no else branch?If no conditions match and there is no
else branch, the program will throw a kotlin.NoWhenBranchMatchedException at runtime.Click to reveal answer
beginner
Write a
when expression that prints "Weekend" for Saturday and Sunday, and "Weekday" for other days.Example code:<br>
val day = "Saturday"
when(day) {
"Saturday", "Sunday" -> println("Weekend")
else -> println("Weekday")
}Click to reveal answer
How do you write multiple conditions in one
when branch in Kotlin?✗ Incorrect
In Kotlin, multiple conditions in a
when branch are separated by commas, like 1, 2, 3 -> ....What keyword do you use to handle all unmatched cases in a
when expression?✗ Incorrect
The
else branch in a when expression handles all cases not matched by previous branches.Can
when be used without an argument to check conditions?✗ Incorrect
When used without an argument,
when checks boolean expressions in each branch.What happens if no
when branch matches and there is no else branch?✗ Incorrect
If no branch matches and no
else is provided, Kotlin throws a NoWhenBranchMatchedException.Which of these is a valid
when branch for multiple values?✗ Incorrect
Multiple values in a
when branch are separated by commas, like 1, 2 -> ....Explain how to use the
when expression with multiple conditions in Kotlin.Think about how you can check if a value matches any of several options.
You got /3 concepts.
Describe the difference between
when with an argument and when without an argument.Consider how <code>when</code> can be used like a switch or like an if-else chain.
You got /3 concepts.