Kotlin if Expression
In Kotlin, if is an expression is which returns a value. It is used for control the flow of program structure. There is various type of if expression in Kotlin.
Traditional if Statement
Syntax of traditional if statement
Syntax of traditional if else statement
Kotlin if-else Expression
As if is an expression it is not used as standalone, it is used with if-else expression and the result of an if-else expression is assign into a variable.
Syntax of if-else expression
Kotlin if-else Expression Example
Let's see an example of if-else expression.
10 is smaller than 20
We can remove the curly braces of if-else body by writing if expression in only one statement.
Using if-else expression in one single line statement is like ternary operator in Java. Kotlin does not support any ternary operator.
Kotlin if-else if-else Ladder Expression
Let's see an example of if-else if-else ladder expression.
10 is positive
Kotlin Nested if Expression
Let's see an example of nested if expression.
body of if 30