Introduction
The when expression helps you choose what to do based on different values, like a smart traffic controller.
The when expression helps you choose what to do based on different values, like a smart traffic controller.
when (variable) { value1 -> action1 value2 -> action2 in range -> action3 else -> defaultAction }
The when expression checks the variable against each case.
The else branch is like a default catch-all if no other case matches.
x is 2.val x = 2 when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") }
y is 5.val y = 5 when (y) { in 1..4 -> println("Between 1 and 4") in 5..10 -> println("Between 5 and 10") else -> println("Out of range") }
obj and prints "It's a string".val obj: Any = "Hello" when (obj) { is String -> println("It's a string") is Int -> println("It's an integer") else -> println("Unknown type") }
This program assigns a letter grade based on the numeric score using when. It prints the score and the grade.
fun main() { val score = 85 val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" in 60..69 -> "D" else -> "F" } println("Score: $score, Grade: $grade") }
You can use when without an argument to check complex conditions.
Each branch can have multiple statements if you use curly braces.
when is a cleaner way to choose actions based on values.
It works like a switch but is more powerful and flexible.
Use else to handle unexpected cases.
when expression in Kotlin?whenwhen expression is used to choose between different actions depending on the value it checks.when.when chooses actions by value [OK]when as a smarter switch [OK]when with loopswhen declares variableswhen with function definitionswhen expression in Kotlin?when syntaxwhen (x) { value -> action } with arrows and braces.when x { 1: println("One") 2: println("Two") else: println("Other") } uses colons (:) instead of arrows (->) and lacks parentheses. switch (x) { case 1: ... } is Java or JavaScript syntax. if (x == 1) ... is an if-else chain.when uses arrows and braces [OK]when [OK]when with switch syntaxval x = 3
when (x) {
1, 2 -> println("Small")
in 3..5 -> println("Medium")
else -> println("Large")
}xx is 3.x with when caseswhen expression:val y = 10
when y {
5 -> println("Five")
10 -> println("Ten")
else -> println("Other")
}when syntaxwhen expression requires parentheses around the variable: when (y).else. The syntax error is missing parentheses around y.y in when -> Option Awhen needs parentheses around the subject [OK]when [OK]when without braceswhen expression to categorize ages into groups: "Child" for 0-12, "Teen" for 13-19, "Adult" for 20-64, and "Senior" for 65 and above. Which when expression correctly implements this?when with condition checkswhen without argument and checks conditions with boolean expressions, which is valid and flexible.when for flexible ranges [OK]when for complex ranges [OK]Pass the test and this pattern moves unknown