0
0
Kotlinprogramming~5 mins

If-else expression assignment in Kotlin

Choose your learning style9 modes available
Introduction

We use if-else expression assignment to choose a value based on a condition in a simple and clear way.

When you want to set a variable to one value if a condition is true, and another value if it is false.
When you want to decide between two options quickly without writing many lines of code.
When you want to keep your code clean and readable by using expressions instead of statements.
When you want to assign a value based on a simple yes/no question in your program.
Syntax
Kotlin
val variable = if (condition) valueIfTrue else valueIfFalse

The if-else here is an expression, so it returns a value.

You must include the else part to cover the false case.

Examples
Assigns the greater of a and b to max.
Kotlin
val max = if (a > b) a else b
Chooses a greeting based on the time of day.
Kotlin
val message = if (isMorning) "Good morning" else "Hello"
Assigns a label depending on whether number is positive or negative.
Kotlin
val sign = if (number >= 0) "Positive" else "Negative"
Sample Program

This program checks the temperature and assigns "Warm" if it is above 20, otherwise "Cold". Then it prints the result.

Kotlin
fun main() {
    val temperature = 15
    val weather = if (temperature > 20) "Warm" else "Cold"
    println("The weather is $weather.")
}
OutputSuccess
Important Notes

If you forget the else part, Kotlin will give an error because the expression must always return a value.

You can use multiple if-else expressions nested or combined with when for more choices.

Summary

If-else expression assignment lets you pick a value based on a condition in one line.

It makes your code shorter and easier to read.

Always include else to handle the false case.