Control Flow - If Expression



' if ' is an expression is which returns a value. It is used to control the flow of the program structure. There is various type of if expression in Kotlin.

  • if-else expression,
  • if-else if-else ladder expression,
  • nested if the expression

if-else expression

The result of an if-else expression is assigned to a variable.
Note : When using if as an expression, you must also include else (required).
fun main(args: Array<String>) {  
val num1 = 10
val num2 =20
val result = if (num1 > num2) {
"$num1 is greater than $num2"
} else {
"$num1 is smaller than $num2"
}
println(result) // 10 is smaller than 20
}
Using if-else expression in one single line statement is like a ternary operator in Java. Kotlin does not support any ternary operator.
Note: You can ommit the curly braces {} when if has only one statement:
fun main(args: Array<String>) {  
val num1 = 10
val num2 =20
val result = if (num1 > num2) "$num1 is greater than $num2" else "$num1 is smaller than $num2"
println(result)
}

if-else if-else Ladder Expression

fun main(args: Array<String>) {  
val num = 10
val result = if (num > 0){
"$num is positive"
}else if(num < 0){
"$num is negative"
}else{
"$num is zero"
}
println(result) //10 is positive
}

Nested if Expression

fun main(args: Array<String>) {  
val num1 = 25
val num2 = 20
val num3 = 30
val result = if (num1 > num2){

val max = if(num1 > num3){
num1
}else{
num3
}
"body of if "+max
}else if(num2 > num3){
"body of else if"+num2
}else{
"body of else "+num3
}
println("$result") // body of if 30
}
..

Comments