0
0
Kotlinprogramming~5 mins

If as an expression returning value in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, if can give back a value. This helps write shorter and clearer code by choosing a value based on a condition.

When you want to pick one value or another based on a condition.
When you want to assign a variable a value depending on a check.
When you want to return a value from a function based on a condition.
When you want to avoid writing extra lines for simple choices.
Syntax
Kotlin
val result = if (condition) value1 else value2

The if expression must have an else part to cover all cases.

You can use multiple lines inside if and else blocks, but the last expression is returned.

Examples
Choose the bigger number between a and b.
Kotlin
val max = if (a > b) a else b
Return "Pass" or "Fail" based on the score.
Kotlin
val message = if (score >= 50) "Pass" else "Fail"
Print a message and return x or -x depending on x.
Kotlin
val result = if (x > 0) {
    println("Positive")
    x
} else {
    println("Not positive")
    -x
}
Sample Program

This program uses if as an expression to find the bigger number and to decide pass or fail.

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

    val score = 45
    val result = if (score >= 50) "Pass" else "Fail"
    println("Result: $result")
}
OutputSuccess
Important Notes

Remember, if as an expression always returns a value.

Without else, if cannot be used as an expression because Kotlin needs to know what to return in all cases.

Summary

if can return a value in Kotlin, making code shorter and clearer.

Always include else when using if as an expression.

You can assign the result of if directly to variables or return it from functions.