In this tutorial, you shall learn about else-if conditional statement in Kotlin, and how to use else-if statement to implement a ladder of conditional logic, with examples.

Kotlin Else-If

Kotlin else-if statement is an extension to the if-else statement. You can check more that one condition in an else-if statement.

Syntax

The syntax of else-if statement is as shown in the following.

if(condition1) {
    //statement(s)
} else if(condition2) {
    //statement(s)
} else if(condition3) {
    //statement(s)
} else {
    //statement(s)
}

There could be as many number of else if blocks as required.

else block is optional as said for if-else statement.

The conditions are evaluated sequentially from top to bottom. If a condition is evaluated to false, the execution continues with the evaluation of subsequent condition. And if the condition evaluates to true, corresponding block of statement(s) is executed and the execution is out of if-else-if statement.

If none of the conditions evaluate to true, runtime executes else block, that too if the else block present.

ADVERTISEMENT

Examples

1. Check if a number is divisible by 2, 3, or 5 using Else-If

In the following program, we check if given number is divisible by 2, 3, or 5 respectively, using an else-if statement. If the number is divisible by 2, you need not to check the divisibility by 3, or 5. Similarly, if the number is divisible by 3, you need not to check the divisibility of the number by 5.

Main.kt

fun main(args: Array<String>) {
    val a = 15

    if(a%2==0) {
        print("$a is divisible by 2.")
    } else if(a%3==0) {
        print("$a is divisible by 3.")
    } else if(a%5==0) {
        print("$a is divisible by 5.")
    } else {
        print("Try another number next time.")
    }
}

In the first if block, we are checking if a is divisible by 2. In the second condition, we are checking is a is divisible by 3 and so on. For the given value of a=15a%3==0 is the first condition that evaluates to true. Hence, corresponding block must be executed.

Let us run the program and verify the output.

Output

15 is divisible by 3.

As discussed, the block corresponding to condition a%3==0 is executed.

2. Else-If statement without else block

We have already gone through through the fact that else block is optional. In the following example, we have write if-else-if statement without else block.

Kotlin Program – example.kt

/**
 * Kotlin If Else If Example
 */
fun main(args: Array<String>) {
    val a = 15

    if(a%2==0) {
        print("$a is divisible by 2.")
    } else if(a%3==0) {
        print("$a is divisible by 3.")
    }
}

Run the program.

Output

15 is divisible by 3.

The condition a%3==0 evaluates to true, hence Kotlin executes the corresponding block.

Conclusion

In this Kotlin Tutorial, we learned what else-if statement is, and how to use it a program with the help of example.