Javatpoint Logo
Javatpoint Logo

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.

  • if-else expression
  • if-else if-else ladder expression
  • nested if expression

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.

Output:

10 is smaller than 20

We can remove the curly braces of if-else body by writing if expression in only one statement.

For example:

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.

Output:

10 is positive

Kotlin Nested if Expression

Let's see an example of nested if expression.

Output:

body of if 30






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA