Kotlin If-else and when expression

 

 

 

 

 

 

 

 

Kotlin if-else

In any programming language if-else is used to implement a conditional check and execute the code accordingly. Like if a certain condition evaluates to TRUE execute a certain code block. These are he following ways in which If-else can be used.


 // Only If
 if (condition) {
        // code to be executed
 }
 
 
 // Single if else
 if (condition) {
        // code to be executed if the condition is true
 } else {
        // code to be executed if the condition is false
 }
 
 
 // If else ladder
if (condition1) {
            // code to be executed if the condition1 is true
} else if (condition2) {
            // code to be executed if the condition2 is false
} else {
            // code to be executed if the none of the above condition evaluates to true
}
 
 
// Nested If else
if (condition) {
            // code to be executed

        if (condition) {
                    // code to be executed if the condition is true
        } else {
                    // code to be executed if the condition is false
        }
}
 

We can also use if-else to assign a variable with the result. If we use the if-else this way, it is an expression.

 
// If-else as expression
var a = if (condition) {
         // some code here
} else {
         
// some code here
}
 

NOTE : In kotlin if-else can be used both as an expression and a statement 

 

KOTLIN When expression

"when" expression is a replacement of the "switch" operator from other languages. It takes an argument and compare it with all the branchesand executes a block of code when the condition is met. Unlike switch operator we don't need to use break in the end of each case. Like If-else,When can also be used both as an expression and a statement.

// when example
when(argument) {
        condition1 -> {
            // some code to be executed
        }
        condition2 -> {
            // some code to be executed
        }
        else -> {
             // some code to be executed
        }
}
 
// When as an expression example
var a = when(condition) {
        case1 -> {
             // some code to be executed
        }
        case2 -> {
             // some code to be executed
        }
        else -> {
             // some code to be executed
        }
}

"else" block is similar to default block in Switch-case from other languages. It is executed when none of the condition are met.
 

NOTE : If "when" is used as a statement else branch is optional. The compiler will check all the conditions inside the when block and if non of the condition matches, the compiler simply exits the block. But in case if "when" is used as an expression "else" block is mandatory.
 

If we do not use the else branch the compiler will throw an error "when" expression must be exhaustive, add necessary 'else' branch

Comments