Hit enter after type your search item

How Kotlin if works?

Kotlin if is an expression that returns a value. This is different if compared with the other languages where if acts as a statement.

As it acts as an expression in Kotlin, so there are no ternary operators (condition ? then : else).

Syntax of Kotlin if expression

As an expression, the if can be used like this:

val max = if (a > b) a else b

It can be used traditionally:

if (expression) //statement to execute

// With else

An example of if expression in Kotlin

This example shows the usage of if in Kotlin as an expression. See how it works:

The result:

The number is 10

The above example shows using if branches as blocks. In that case, the last expression is the value of the block. For example:

The output:


As the value of variable a is not greater than b, so else part is True and so ‘b’ is the block value.

Traditional usage of Kotlin if

In the following example, the if is used as a statement (the way that you might be used too):

The result:

Number is something other than 20!

How to use if..elseif..else in Kotlin?

We have seen how to use if and else as expression and statement. In both cases, we came across only two options. How to deal if you have more than two blocks of codes or options to check?

In other languages, we use if and elseif; Kotlin also provides “else if” if you have more than two blocks of codes. This is called if..else..if ladder in Kotlin.

The example below uses four blocks:

The output:

The color is black

An example of leap year using if expression

As you run the following code, the user is asked to enter a year. The entered value is converted to an int and then we calculate whether it’s a leap year or not inside the if expression.

The result is displayed as the last line:

The result as I entered 2016:

Kotlin if expression

You can see, the result is ‘Leap year’. Try entering different years and see the result yourself in your Kotlin editor.

Note: Leap year has two other conditions:

  • (i) Year is not divisible by 100. For example, 1900 is not a leap year, although it can be divided by 4.
  • (ii)Year can be divided by 400 is a leap year. For example, 2000 is a leap year as it can be divided by 400 (though it can be divided by 100 as well).
  • (iii)You need to incorporate these two conditions as well in the above code by using if..else if..else ladder
This div height required for enabling the sticky sidebar