0
0
Kotlinprogramming~3 mins

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

Choose your learning style9 modes available
The Big Idea

What if your conditions could instantly give you answers without extra steps?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var message: String
if (hour < 12) {
    message = "Good morning"
} else {
    message = "Good evening"
}
After
val message = if (hour < 12) "Good morning" else "Good evening"
What It Enables

This lets you write shorter, clearer code that directly produces values from conditions, making your programs easier to write and maintain.

Real Life Example

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.

Key Takeaways

If can return a value, not just control flow.

This reduces code length and errors.

It makes your code easier to read and write.