0
0
Kotlinprogramming~3 mins

Why When as expression returning value in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace messy if-else checks with a simple, powerful tool that returns values instantly?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
var message: String
if (fruit == "Apple") {
  message = "You picked an apple!"
} else if (fruit == "Banana") {
  message = "You picked a banana!"
} else {
  message = "Unknown fruit"
}
After
val message = when (fruit) {
  "Apple" -> "You picked an apple!"
  "Banana" -> "You picked a banana!"
  else -> "Unknown fruit"
}
What It Enables

You can write clean, clear code that chooses values based on many conditions without repeating yourself.

Real Life Example

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.

Key Takeaways

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.