0
0
Kotlinprogramming~3 mins

Why expressions over statements matters in Kotlin - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your code could answer questions directly instead of following long instructions?

The Scenario

Imagine you want to decide what to wear based on the weather. You write a list of instructions: if it's cold, wear a jacket; if it's warm, wear a t-shirt. You have to write each step separately and remember to update the outfit variable each time.

The Problem

This step-by-step way is slow and easy to mess up. You might forget to set the outfit, or write extra lines that make your code longer and harder to read. It feels like giving orders instead of just getting the answer you want.

The Solution

Using expressions means every piece of code gives back a value. Instead of telling the computer what to do step by step, you ask it for the answer directly. This makes your code shorter, clearer, and less likely to have mistakes.

Before vs After
Before
var outfit: String
if (temperature < 15) {
    outfit = "Jacket"
} else {
    outfit = "T-shirt"
}
After
val outfit = if (temperature < 15) "Jacket" else "T-shirt"
What It Enables

It lets you write clean, simple code that directly produces results, making your programs easier to understand and maintain.

Real Life Example

Choosing a meal based on time of day: instead of writing many steps to set the meal, you can use an expression that picks breakfast, lunch, or dinner in one clear line.

Key Takeaways

Expressions return values, statements do not.

Using expressions makes code shorter and clearer.

It reduces mistakes by combining decision and assignment in one step.