0
0
Kotlinprogramming~5 mins

Why expressions over statements matters in Kotlin

Choose your learning style9 modes available
Introduction

Expressions produce values and can be used anywhere, while statements just do actions. Using expressions makes code simpler and easier to read.

When you want to assign a value directly from a condition or calculation.
When you want to write shorter and clearer code without extra variables.
When you want to use the result of a block of code immediately.
When you want to avoid repeating code by using expressions inside other expressions.
When you want to write functional-style code that is easier to test and maintain.
Syntax
Kotlin
val result = if (condition) value1 else value2
In Kotlin, if is an expression that returns a value.
Expressions can be used inside assignments or other expressions.
Examples
This assigns the greater of a or b to max using an if expression.
Kotlin
val max = if (a > b) a else b
The when expression returns a string based on the value of score.
Kotlin
val message = when (score) {
  in 90..100 -> "Excellent"
  in 75..89 -> "Good"
  else -> "Try again"
}
The Elvis operator ?: is an expression that returns the left value if not null, otherwise the right value.
Kotlin
val length = list?.size ?: 0
Sample Program

This program shows how if and when are expressions that return values used directly in assignments.

Kotlin
fun main() {
    val a = 10
    val b = 20
    val max = if (a > b) a else b
    println("The maximum is $max")

    val score = 85
    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        in 70..79 -> "C"
        else -> "F"
    }
    println("Your grade is $grade")
}
OutputSuccess
Important Notes

Expressions help reduce the need for extra variables and make code more concise.

Using expressions encourages thinking about what value a piece of code produces, not just what it does.

Summary

Expressions return values and can be used anywhere a value is needed.

Statements perform actions but do not return values.

Using expressions leads to clearer, shorter, and more maintainable code.