What if your conditions could instantly give you answers without extra steps?
Why If as an expression returning value in Kotlin? - Purpose & Use Cases
Imagine you want to pick a message based on a condition, like greeting someone differently if it's morning or evening. Without using expressions, you write separate code blocks for each case and then assign the result manually.
This manual way means writing extra lines, repeating yourself, and risking mistakes like forgetting to assign the result. It feels clunky and makes your code longer and harder to read.
Kotlin lets you use if as an expression that returns a value directly. This means you can write your condition and get the result in one simple line, making your code cleaner and easier to understand.
var message: String if (hour < 12) { message = "Good morning" } else { message = "Good evening" }
val message = if (hour < 12) "Good morning" else "Good evening"
This lets you write shorter, clearer code that directly produces values from conditions, making your programs easier to write and maintain.
Think about deciding a discount based on a customer's membership level. Using if as an expression, you can assign the discount in one line instead of multiple steps.
If can return a value, not just control flow.
This reduces code length and errors.
It makes your code easier to read and write.