Kotlin if Expression

In this tutorial you will learn about kotlin if, else and nested if else expression.

The if expression is definitely one of those constructs which lets us simplify our task of determining conditions during a program flow. Or rather, for performing any decisions in the program we look up to the if statement first, before considering any other because of our sheer familiarity with the statement and efficiency of the same. The latter part however, by and large depends on our problem statement. The if statement hence, is an integral part of any programming language.

if else expression kotlin

Kotlin, however has a new modification to offer. In this language the choice is given to the programmer whether he has to use the if as a statement or as an expression. Yes, in Kotlin, rather than just being a branching statement; if can even be used to return any value i.e., it can be used as an expression, here’s how this works.

if else Expression

In contrast to the traditional usage of the if statement as in java, c++, c# where in the if statement simply lets us perform or execute a block of statement following its branching property; the if expression lets us work with a value. It is capable of returning a value too. Let us see how:

Traditional Usage:

Example:

Using if as Expression:

Here, in this example, the value of b gets returned to the variable maximum.

Note:

  • When using if as expression (returning value or assigning to variable) then it must have else block.
  •  In case if or else block contain more than one statement then last statement is returned as value.
  • Curly braces are optional in case the block contain only one statement.

Nested if else Expression

The nested if else construct is just the if else construct coiled up into some other if else constructs. The number of if else constructs we want to include in some other if else construct is totally dependent on the programmer according to the program code requirements. Here is how this works:

Traditional Usage:

Example:

Output: b is greater

Using as Expression:

Output: a is greater

Therefore to conclude, we can say the usage of if  statement has been extended to an if expression in Kotlin language and that gives a new dimension to this language by means of which if can even be used to return values.

Mention in comments if you have queries regarding above tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.