Kotlin If..Else Expressions

In Kotlin, the if statement can be used as an expression, which means it returns a value that can be assigned to a variable or used in other expressions. When used as an expression, the if statement must have both a then and an else block, and the last expression in each block is used as the return value.

Here’s the basic syntax for using if as an expression in Kotlin:

val result = if (condition) {
    // code to execute if the condition is true
    value1
} else {
    // code to execute if the condition is false
    value2
}

In this example, if the condition is true, the code inside the first block will be executed and value1 will be returned. If the condition is false, the code inside the second block will be executed and value2 will be returned. The final value is assigned to the variable result.

Here’s an example of using if as an expression in Kotlin:

fun main() {
    val a = 10
    val b = 5

    val max = if (a > b) a else b

    println("The maximum value is: $max")
}

In this example, we have two variables a and b that contain values of 10 and 5, respectively. We use the if statement as an expression to compare the values of a and b. If a is greater than b, the value of a is returned and assigned to the variable max. If a is not greater than b, the value of b is returned and assigned to max. In this case, since a is greater than b, the value of a which is 10 is assigned to max. The message “The maximum value is: 10” will be printed to the console.

In Kotlin, you can use the ternary operator as a simplified version of the if-else statement. The ternary operator is a shorthand way of writing an if-else statement that returns a value.

Here’s the basic syntax for using the ternary operator in Kotlin:

val result = if (condition) value1 else value2

In this example, if the condition is true, value1 is returned, otherwise value2 is returned. The final value is assigned to the variable result.

Here’s an example of using the ternary operator in Kotlin:

fun main() {
    val a = 10
    val b = 5

    val max = if (a > b) a else b

    println("The maximum value is: ${if (a > b) a else b}")
}

In this example, we have two variables a and b that contain values of 10 and 5, respectively. We use the if statement as a ternary operator to compare the values of a and b. If a is greater than b, the value of a is returned, otherwise the value of b is returned. The final value is assigned to the variable max. We also print the message “The maximum value is: 10” to the console using string interpolation.

Using the ternary operator can make your code more concise and easier to read, especially when you have simple if-else statements that return a single value. However, it’s important to use it judiciously and not overuse it, as it can make your code harder to read and understand if used excessively.

NOTE: ‘if’ must have both main and ‘else’ branches if used as an expression.