Kotlin if else Statements Tutorial

In this section, we will learn what the if else statement is and how to use it in Kotlin.

Kotlin if else Statement (AKA if-then statement)

The if-else statement is a way of branching the path of executions in a program and create conditional statements in Kotlin!

For example, let’s say part of your program is to check and see if the value of a variable is equal or greater than another value; if it was, then only in that case you want to run a specific set of instructions! Otherwise, your program might need to run another set of instructions!

This is branching and using the if-else statement, we can create such type of logics.

For example, let’s say your program’s job is to take the password from a user and match it against the database. Now if the password was correct, you want to allow the person to enter to the program, but if the result was false, then you want to show an error message saying the password is wrong and ask the user to enter another password, etc.

These are conditional statements and using the if-else statement, we can easily create them.

 

Alright, let’s get into the syntax of this statement and after that we will see how the if-else statement works practically.

Kotlin if-else Syntax:

if (condition) {

#instructions of the if statement to be run if the condition resulted true

}else{

#instructions of the else statement to be run if the condition resulted false.

}

if: in order to create an if statement, we start with the keyword if.

(condition): every if statement has a condition part that comes inside the pair of parentheses we put after the if statement. The condition we set here must result either true or false. If the result of the condition was true, then the body of the if statement will run. Otherwise, if the condition resulted false, it’s the body of the else statement that will be run instead.

{}: the pair of braces that comes after the if statement defines the body of this statement! Any instructions we put within this body will be executed if the condition of the statement resulted true.

else: the else statement is like the plan B in your program! Basically, if the condition of the if statement resulted true, it’s the body of the if statement that runs and any instructions there will be executed. But if the condition of the if statement resulted false, it’s the body of the else statement to be run. So this is where we put the instructions that should run if the condition resulted false.

Notes:

  • The else statement does not have any condition.
  • The pair of curly braces we set after the else statement defines its body. So any instructions you put there will be executed if the result of the if condition was false.
  • Using the else statement is optional and you can remove it from an if statement!
  • We can use the if statement on its own but we can’t use an else statement on its own without an if statement! It must come after an if statement.
  • Only the instructions of the if statement or else statement runs (depending on the result of the condition) but not both.

Example: using if else in Kotlin

fun main(){
    var age = 100 
    var salary = 200000

    if (age == 100){
        println("The value of the age variable is 100")
    }else {
        println("The value of the age variable is not 100")
    }

    if (salary > 300000){
        println("Your salary is above 300000")
    }else{
        println("The salary is less than 300000")
    }

}

Output:

The value of the age variable is 100

The salary is less than 300000

How Does if-else Statement Work in Kotlin?

In this example, we have two if statements.

The condition of the first if statement is to check and see if the value of the age variable is equal to 100. Now, because the value of the age variable is equal to 100, then the result of this condition becomes true and that’s how the instructions within the body of the first if statement ran.

Now in the next if statement we can see that the condition of the if statement does not result true! Basically, the value of the salary variable is not higher than the value 300000. So for this reason, the body of the if statement is skipped and the else statement ran instead.

Kotlin if-else-if (AKA ladder) statement

So far we’ve seen that using if-else statements we can set one condition and if that condition resulted true, then the body of the if statement will run. Otherwise it’s the body of the else statement that runs instead.

But what if we had other conditions and a set of instructions that wanted to be executed if those conditions resulted true then? For example, let’s say a user entered a number into our program. Now we want to see if the value is in the range of 100 to 200. If it was, then a specific task should run. But if it wasn’t, we still have other conditions to be checked! For example, now we want to see if the value is between the range of 500 to 1000 and if it was, then wanting to run another task specific for that range!

This is where we want to use the else if clause!

This clause comes after an if statement (it’s part of the if statement) and makes developers to be able to add more branches (more conditions and blocks) to an if statement.

Alright, before we get into the details of the else if clause, let’s see its syntax first and then from there we will continue our discussion on how this clause works in Kotlin.

Kotlin if-else-if Syntax

if (condition){

}else if (condition){

} else if (condition_n){

}else{

}

else if: the else if clause comes after the if statement and we can add one or as many else if clause to an if statement.

Here the program first checks the condition of the if statement and if the result of that was true, it will run the body of the if statements and ignore the rest of else if blocks altogether! (Meaning none of them will be checked!)

But if the condition of the if statement resulted false, then the else-if clauses will be checked in order and one by one until the condition of one of them results true and the body of that else if runs! Note that the first else if clause that results true, the rest of else if statements will be skipped and your program will continue to run the rest of instructions after the entire if else if statements.

Also, if none of the if or else if statements resulted true, in that case only, the else statement will be executed (if there was one of course).

 

Example: using Kotlin if-else-if statement

fun main(){
    var age = 100 
    
    if (age == 40){
        println("The value of the age variable is 40")
    }else if (age == 50){
        println("The value of the age variable is 50")
    }else if (age == 80){
        println("The value of the age variable is 80")
    }else if(age == 100){
        println("The value of the age variable is 100")
    }else{
        println("The value is unknown")
    }

}

Output:

The value of the age variable is 100

Here the condition of the if and else if statements is to check the value of the age variable against a number. Now the condition of the if statement results false, then the first else if clause is checked, and that resulted false as well. This process continues for the next one which it resulted false as well, but the condition of the last else if clause resulted true and so its body is executed.

Now because the last else if statement resulted true, then the else clause of this program is skipped because there’s no reason for it to be run anymore.

Example: Kotlin else statement

As mentioned before, the use of else statement is optional when it comes to if-else. This means we can have just one if statement without any else clause.

fun main(){

    var age = 200 

    if (age == 100){
        println("The value of the age variable is 100")
    }
    println("End")
}

Output:

End

Note that here the condition of the if statement did not result true and we didn’t have any else clause as the backup plan to be run. That’s how we got only the word “End” on the output stream.

Kotlin Nested if..else statement

The body of the if or else statement is a place where we can put any sort of instructions there. This includes using another if statement! This might be necessary if we want to run another conditional statement based on another value within the body of an if or else statement.

In short, using an if statement within the body of another if statement is called nested if statement.

Example: creating nested if..else statement in Kotlin

fun main(){

    var age = 30
    var money = 400
    if (age > 21){
        if (money > 200){
            println("The person can enter to the bar")
        }else{
            println("The person has the right age but not enough money to enter the bar")
        }
    }else{
        println("This person can't enter to the bar because he is under age!")
    }
    println("End")
}

Output:

The person can enter to the bar

End

More to Read

Kotlin ternary operator

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies