0
0
Kotlinprogramming~5 mins

When expression as powerful switch in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Awhen
Bif
Ccase
Dselect
Can when in Kotlin check for ranges like 1..5?
AOnly with enums
BNo, only exact matches
COnly for strings
DYes, it supports ranges
What must you include in a when expression to handle unmatched cases?
Adefault
Belse
Ccatch
Dfinally
Is when in Kotlin a statement or an expression?
ABoth statement and expression
BOnly an expression
COnly a statement
DNeither
Which of these can when NOT match against?
AExact values
BArbitrary conditions
CFunction definitions
DRanges
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.