0
0
Kotlinprogramming~5 mins

When without argument in Kotlin

Choose your learning style9 modes available
Introduction

The when expression without an argument lets you check multiple conditions easily, like a cleaner if-else chain.

When you want to check different conditions that are not based on a single value.
When you want to replace multiple <code>if-else</code> statements for better readability.
When you want to run different code blocks based on boolean expressions.
When you want to handle complex decision making with clear and simple syntax.
Syntax
Kotlin
when {
    condition1 -> action1
    condition2 -> action2
    else -> defaultAction
}

Each condition is a boolean expression.

The else branch is optional but recommended to cover all cases.

Examples
This checks where x fits and prints a message accordingly.
Kotlin
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")
}
Checks conditions on the string name without using a single argument.
Kotlin
val name = "Alice"
when {
    name.startsWith("A") -> println("Name starts with A")
    name.length > 5 -> println("Name is long")
    else -> println("Name is short")
}
Sample Program

This program prints a message about the weather based on the temperature using when without an argument.

Kotlin
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")
    }
}
OutputSuccess
Important Notes

Using when without an argument is like writing multiple if checks but cleaner.

Make sure conditions do not overlap to avoid unexpected results.

Summary

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.