How to Use When Without Argument in Kotlin: Simple Guide
In Kotlin, you can use
when without an argument to evaluate boolean conditions directly. Each branch uses a condition that returns true or false, and the first true condition's block runs. This makes when act like an elegant replacement for multiple if-else statements.Syntax
The when expression without an argument uses boolean conditions in each branch. It looks like this:
when {starts the expression.- Each branch has a condition that returns
trueorfalse. - The first branch with a
truecondition executes. elsebranch is optional but recommended as a fallback.
kotlin
when {
condition1 -> {
// code if condition1 is true
}
condition2 -> {
// code if condition2 is true
}
else -> {
// code if none above are true
}
}Example
This example shows how to use when without an argument to check a number's range and print a message accordingly.
kotlin
fun main() {
val number = 15
when {
number < 0 -> println("Number is negative")
number in 0..10 -> println("Number is between 0 and 10")
number in 11..20 -> println("Number is between 11 and 20")
else -> println("Number is greater than 20")
}
}Output
Number is between 11 and 20
Common Pitfalls
Common mistakes when using when without an argument include:
- Forgetting that each branch must be a boolean condition.
- Not including an
elsebranch, which can cause a runtime error if no conditions match. - Using expressions that do not return boolean values in branches.
kotlin
fun main() {
val x = 5
// Wrong: branch condition is not boolean
/*
when {
x -> println("x") // Error: x is Int, not Boolean
else -> println("else")
}
*/
// Right way:
when {
x > 0 -> println("x is positive")
else -> println("x is zero or negative")
}
}Output
x is positive
Quick Reference
Tips for using when without argument:
- Use boolean expressions in each branch.
- Always provide an
elsebranch to handle unexpected cases. - It works like a cleaner
if-else ifchain.
Key Takeaways
Use when without argument to evaluate boolean conditions directly.
Each branch must be a boolean expression returning true or false.
The first true condition's block runs; else branch handles all other cases.
It simplifies multiple if-else statements into a clean, readable structure.
Always include an else branch to avoid missing cases.