Introduction
The when expression without an argument lets you check multiple conditions easily, like a cleaner if-else chain.
The when expression without an argument lets you check multiple conditions easily, like a cleaner if-else chain.
when { condition1 -> action1 condition2 -> action2 else -> defaultAction }
Each condition is a boolean expression.
The else branch is optional but recommended to cover all cases.
x fits and prints a message accordingly.val x = 10 when { x < 5 -> println("x is less than 5") x in 5..15 -> println("x is between 5 and 15") else -> println("x is greater than 15") }
name without using a single argument.val name = "Alice" when { name.startsWith("A") -> println("Name starts with A") name.length > 5 -> println("Name is long") else -> println("Name is short") }
This program prints a message about the weather based on the temperature using when without an argument.
fun main() { val temperature = 25 when { temperature < 0 -> println("Freezing cold") temperature in 0..20 -> println("Cool weather") temperature in 21..30 -> println("Warm weather") else -> println("Hot weather") } }
Using when without an argument is like writing multiple if checks but cleaner.
Make sure conditions do not overlap to avoid unexpected results.
when without argument checks boolean conditions one by one.
It is a neat way to replace multiple if-else statements.
Always consider adding an else branch to handle all cases.
when without argument do in Kotlin?when without argumentwhen evaluates each condition as a boolean expression.when with argument, it does not match values but checks conditions one by one.when without argument = boolean checks [OK]when without argument in Kotlin?when without argument syntaxval x = 10
when {
x < 5 -> println("Less than 5")
x in 5..10 -> println("Between 5 and 10")
else -> println("More than 10")
}when without argument:val y = 3
val result = when {
y > 5 -> println("Greater than 5")
y < 5 -> println("Less than 5")
}when branchesval temp = 25
when {
temp <= 0 -> println("Freezing")
temp in 1..15 -> println("Cold")
temp in 16..25 -> println("Warm")
temp > 25 -> println("Hot")
else -> println("Unknown")
}when usage correct?Pass the test and this pattern moves unknown