If Expression in Kotlin

You are here:
Estimated reading time: 4 min

In this tutorial, we will be learning control flows in Kotlin using if expression.

We will also talk about other conditional statements such as:

  • If-else
  • If-else-if ladder
  • Nested If-else

If is one of the conditional statements in Kotlin. Conditional statements are used to make decisions. These statements have a condition that evaluates to either true or false.

If the condition evaluates to true, the conditional statement’s body is executed. If the condition evaluates to false, the conditional statement’s body is skipped or bypassed.

Syntax

if(condition){
        //if block code
    }

Kotlin’s if also has an optional else block.

When the given condition evaluates to true, the if block is executed.

When the condition evaluates to false, then this else block is executed. The syntax for if-else is given below:

if(condition){
        //if block code
    }
    else{
        //else block code
    }

In Kotlin, if can be used as a statement as well as an expression (it may return some value). We will learn how to implement it in both ways.

if as a Statement

When used as a statement, if does not return any value. The if statement allows us to specify a block of code that can only be executed when the given condition evaluates to true.

fun main(){
    var x=2
    if(x>1){
        println("Hello, World!")
        println("I am Kotlin.")
    }
    println("Goodbye!")
}

In the given example, the value of x is 2. When checked with the condition in the if statement, the result evaluates to true (as 2 is greater than 1). Therefore, the if block is executed and the statements, “Hello, World!” and “I am Kotlin.” are printed out. After the execution of if block, the control exits out of the if block and then “Goodbye!” statement is printed out to the console.

If the condition evaluated to false, then the if block would not have been executed (i.e. it would have been skipped and the control would have been directly shifted to statements written after the if block) and instead only the “Goodbye!” statement would have been printed out to the console.

if as an Expression/if as Ternary Operator

Unlike Java, Kotlin’s if can also work as an Expression i.e. it can return a value.

In this way, Kotlin’s if block easily replaces the ternary operator in Java.

When used as an expression, the if block MUST be followed by an else block.

fun main(){
    var x=5
    var z=if(x>1){
        "Hello!"
    }
    else{
        "Goodbye!"
    }
    println(z)
}

In the given example, the value of the variable x is 5. When this x is checked with the condition mentioned in the if block, the result evaluates to true (as 5 is greater than 1). Therefore, the if block is executed and the string “Hello!” is assigned to the variable z. After the if block is executed completely, the control exits the if block, skips the else block (as the else block is only ever executed if the condition in the if block evaluates to false), and then shifts to statements written after the else block, where the value of the variable z is printed out to the console.

If the condition had evaluated to false, then the if block would not have been executed and instead, the else block would have been executed. Therefore, the string “Goodbye!” would have been assigned to the variable z.

Note:

When used as an expression, if the if-block and else-block have multiple statements inside them, then the last statement is taken as the return value.

fun main(){
    var age = 12
    var voter_val = if(age>=18){
        println("Age is greater than or equal to 18")
        println("The voter validity status is stored in variable voter_val")
        "Valid"
    }
    else{
        println("Age is less than 18")
        println("The voter validity status is stored in variable voter_val")
        "Invalid"
    }
    println("The validity status is -> $voter_val")
}

Output:

Kotlin If expression output

Kotlin If-Else One Liner

Kotlin’s if-else can also be written in a single line as shown below:

fun main() {
    var x = if(2>1) "Hello" else "Bye"
    println(x)
}

In the above example, the value of x will turn out to be “Hello”.

This form of writing if-else is known as Kotlin if-else shorthand form.

if-else-if Ladder

To check more than one condition, multiple if-else-if blocks can be chained together.

Syntax – if-else Ladder

if(condition){
        //if body
    }
    else if(condition 2){
        //else if body
    }
    else if(condition 3){
        //else if body
    }
    else{
        //else body
    }

Example

fun main(){
    var x = 25
    if(x<10){                   //if block
        println("Less than 10")
    }
    else if(x<20){             //First else if
        println("Between 10 and 20")
    }
    else if(x<30){             //Second else if
        println("Between 20 and 30")
    }
    else{                      //else block
        println("Greater than 30")
    }
}

In the above example, the following steps take place:

  1. The value of x is checked with the condition mentioned in the if block. This evaluates to false, as 25 is not less than 10.
  2. Then, the control shifts to the first else if block and the value of x is checked with the condition in this else if block. This, too, evaluates to false, as 25 is not less than 20.
  3. Now, the control shifts to the second else if block and the value of x is checked with the condition in this else if block, which evaluates to true as 25 is less than 30.
  4. As a result, the second else if block’s body is executed.
  5. After execution, the control exits the second else if block, skips the else block, and then shifts to statements after the if-else-if ladder/chain.

Nested if/Nested if-else

Nested if/Nested if-else means having an if (or if-else) statement inside another if (or if-else) statement.

Syntax – Nested if

if(condition){
        if(condition){
            //if body
        }
}

Syntax – Nested if-else

if(condition){
        if(condition){
            //if body
        }
        else{
            //else body
        }
    }
    else{
        if(condition){
            //if body
        }
        else{
            //else body
        }
    }

Examples

fun main(){
    var x = 25
    var y = 10
    var z = 30
    if(x>y){
        if(x>z){
            println("Value of x is $x")
            println("x is the largest number.")
        }
        else{
            println("Value of z is $z")
            println("z is the largest number.")
        }
    }
    else{
        if(y>z){
            println("Value of y is $y")
            println("y is the largest number.")
        }
        else{
            println("Value of z is $z")
            println("z is the largest number.")
        } 
    }
}

Another type of conditional statement in Kotlin is the when block. To learn more about when in Kotlin, refer to our tutorial here.

As mentioned earlier, Kotlin’s if can also be used as an expression, unlike Java. To learn more about the differences between Java and Kotlin, refer to our article here.

Check out our list of comprehensive and in-depth Kotlin articles: https://kotlintutorials.com/

References:

https://kotlinlang.org/docs/tutorials/kotlin-for-py/conditionals.html

https://en.wikipedia.org/wiki/Kotlin_(programming_language)

Was this article helpful?
Dislike 0
Views: 23