0
0
Kotlinprogramming~5 mins

When with multiple conditions in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ASeparate conditions with commas
BUse && between conditions
CUse || between conditions
DWrite multiple <code>when</code> expressions
What keyword do you use to handle all unmatched cases in a when expression?
Adefault
Bcatch
Celse
Dfinally
Can when be used without an argument to check conditions?
AYes, it can check boolean expressions
BOnly with strings
COnly with integers
DNo, it always needs an argument
What happens if no when branch matches and there is no else branch?
AReturns null
BThrows an exception
CProgram continues silently
DReturns zero
Which of these is a valid when branch for multiple values?
A1 && 2 -> ...
B1 || 2 -> ...
C1 to 2 -> ...
D1, 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.