Kotlin - if-else-if Statement Example

A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.

Syntax:

Syntax:

if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.

Kotlin - if-else-if Statement Example

package net.javaguides.kotlin

fun main(args: Array < String > ) {

    var age = 17
    if (age < 12) {
        println("Child")
    } else if (age in 12. .17) {
        println("Teen")
    } else if (age in 18. .21) {
        println("Young Adult")
    } else if (age in 22. .30) {
        println("Adult")
    } else if (age in 30. .50) {
        println("Middle Aged")
    } else {
        println("Old")
    }
}
Output:
Teen

Comments