
If Else Expression in Kotlin
📌 If-Else Expression in Kotlin
In Kotlin, if
and else
are used for conditional decision-making. Unlike some other languages, Kotlin treats if-else
as an expression, meaning it can return a value. This makes it more flexible and concise.
✅ 1. Basic If-Else Statement
You can use if-else
like a traditional conditional statement.
📌 Example:
fun () { val number = 10 if (number > 0) { println("$number is positive") } 10 is positive
if
checks the conditionnumber > 0
else
executes when the condition isfalse
✅ 2. If-Else Expression
In Kotlin, if-else
can be used as an expression to return a value.
📌 Example:
fun () { val a = 15 val b = 20 val max = if (a > b) a else b println("The maximum value is $max")}
Output:
The maximum fun () { val number = -5 val result = if (number > 0) { "Positive" } else if (number < 0) { "Negative" } else { "Zero" } println("The number is $result")}
Output:
The number fun () { val a = 10 val b = 20 val c = 15 val max = if (a > b) { if (a > c) a else c } else { if (b > c) b else c } println("The maximum value is $max")}
Output:
The maximum fun main() { val age = 18 if (age >= 18) { println("Eligible to vote") } println("Program completed")}
Output:
Eligible to voteProgram completed
If the condition is
true
, the statement executes.If
false
, it skips the block and moves on.
✅ 6. Conclusion
Use
if-else
as a statement for conditional logic.Use
if-else
expressions to return values.Combine multiple conditions using
else if
.Use nested if-else for complex decisions.
Kotlin's
if
is more powerful and concise compared to other languages.