In this tutorial you will learn about the Kotlin if expression and its application with practical example.
Kotlin if Expression
Block of statement executed only when a specified condition is true.
Table Of Contents−
Syntax:-
1 2 3 |
if(condation){ // statement(s) to be executed when condition is true } |
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var x= 20 if (x > 10) { print("x is greater") } } |
Output:-
1 |
x is greater |
Kotlin if…else Expression
When we want to execute some block of code if a condition is true and another block of code if a condition is false, In such a case we use if….else statement.
Syntax:-
1 2 3 4 5 6 |
if (condition) { // statement(s) to be executed when condition is true } else { // statement(s) to be executed when condition is false } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main(args: Array<String>) { var a = 10 var b = 20 if (a > b) { println("a is greater than b") } else { println("b is greater than a") } } |
Output:-
1 |
b is greater than a |
Kotlin if..else..if Ladder Expression
The if..else..if Ladder statement is used to select one of among several blocks of code to be executed.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { var a = 10 var b = 10 if (a > b) { println("a is greater than b") } else if(a == b){ println("a and b are equal") } else{ println("b is greater than a") } } |
Output:-
1 |
a and b are equal |
Kotlin Nested if Expression
When there is an if statement inside another if statement then it is known as nested if else.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fun main(args: Array<String>) { var a = 4 var b = 6 var c = -3 var max = if (a > b) { if (a > c) a else c } else { if (b > c) b else c } println("max = $max") } |
Output:-
1 |
max = 6 |