What if you could replace messy if-else checks with a simple, powerful tool that returns values instantly?
Why When as expression returning value in Kotlin? - Purpose & Use Cases
Imagine you have a list of fruits and you want to print a special message for each type. Without a smart tool, you write many if-else checks for each fruit manually.
This manual way is slow and messy. You might forget a case or write repeated code. It's hard to read and fix later, especially when you add more fruits.
The when expression in Kotlin lets you check many conditions clearly and returns a value directly. It makes your code shorter, easier to read, and less error-prone.
var message: String if (fruit == "Apple") { message = "You picked an apple!" } else if (fruit == "Banana") { message = "You picked a banana!" } else { message = "Unknown fruit" }
val message = when (fruit) {
"Apple" -> "You picked an apple!"
"Banana" -> "You picked a banana!"
else -> "Unknown fruit"
}You can write clean, clear code that chooses values based on many conditions without repeating yourself.
Think about a vending machine that gives different messages depending on the button pressed. Using when makes it easy to return the right message for each button.
When as expression returns a value directly, simplifying your code.
It replaces long if-else chains with clear, readable branches.
Helps avoid mistakes and makes adding new cases easy.