Kotlin else if statement

In Kotlin, else if is used to chain multiple conditions together in a conditional statement. It allows you to test multiple conditions and execute different code blocks based on the result of each test.

The basic syntax for using else if in a conditional statement is as follows:

if (condition1) {
    // code to execute if condition1 is true
} else if (condition2) {
    // code to execute if condition1 is false and condition2 is true
} else {
    // code to execute if both condition1 and condition2 are false
}

In this example, the if statement checks the value of condition1. If condition1 is true, the code inside the first block will be executed. If condition1 is false, the else if statement checks the value of condition2. If condition2 is true, the code inside the second block will be executed. If both condition1 and condition2 are false, the code inside the else block will be executed.

Here’s an example of using else if in Kotlin:

fun main() {
    val grade = 85

    if (grade >= 90) {
        println("A")
    } else if (grade >= 80) {
        println("B")
    } else if (grade >= 70) {
        println("C")
    } else if (grade >= 60) {
        println("D")
    } else {
        println("F")
    }
}

In this example, we have a variable grade that contains a value of 85. We use the if statement to check the value of grade. If grade is greater than or equal to 90, the code inside the first block will be executed, which prints out the letter “A”. If grade is between 80 and 89, the code inside the second block will be executed, which prints out the letter “B”. If grade is between 70 and 79, the code inside the third block will be executed, which prints out the letter “C”. If grade is between 60 and 69, the code inside the fourth block will be executed, which prints out the letter “D”. If grade is less than 60, the code inside the else block will be executed, which prints out the letter “F”. In this case, since grade is 85 which is between 80 and 89, the message “B” will be printed to the console.