Kotlin – Conditional Expression
Kotlin conditional expression can be used to select an expression based on given condition.
Syntax
The syntax of conditional expression in Kotlin is
if <condition> <expression_1> else <expression_2>
If the condition evaluates to true
, then this conditional expression returns expression_1
.
If the condition evaluates to false
, then this conditional expression returns expression_2
.
We can also nest conditional expressions in Kotlin. We shall learn about that in the examples.
Examples
1. Find maximum of two numbers using Conditional Expression
In the following program, we will define a conditional expression to find the maximum of two numbers a
and b
.
Main.kt
fun main(args: Array<String>) {
val a = 10
val b = 25
val max = if (a > b) a else b
print("Maximum of $a and $b is $max.")
}
Output
Maximum of 10 and 25 is 25.
We can also write a nested conditional expression, just like nested if else statement.
Let us find out the maximum of three numbers: a
, b
and c
, using conditional expression.
Main.kt
fun main(args: Array<String>) {
val a = 10
val b = 25
val c = 11
val max = if (a > b && a > c) a else if (b > c) b else c
print("Maximum of $a, $b and $c is: $max.")
}
Output
Maximum of 10, 25 and 11 is: 25.
Conclusion
In this Kotlin Tutorial, we learned how to write conditional expressions, and nested conditional expressions in Kotlin, with examples.