In this topic, we'll explore Kotlin's conditional expressions, focusing on the various forms of the if expression and its usage as an expression-style construct.
Conditional expressions
Conditional expressions allow a program to perform different computations based on the value of a boolean expression. There are different forms of conditional expressions, such as the single if case, if-else cases, if-else-if cases, and nested if's.
Expression-style "if"
Unlike the case of some other programming languages, Kotlin's if is an expression, not a statement. This means it can return a value as a result of computations. The result must be the last expression in the body. For example:
val max = if (a > b) {
println("Choose a")
a
} else {
println("Choose b")
b
}
In the above example, the variable max is assigned the value of the last expression in the body. It's important to note that if you use an expression-style if, it must have an else branch.
You can skip braces if all the bodies contain only a single statement:
val max = if (a > b) a else b
There are cases when you don't need to declare a new variable for storing a result. For instance, consider the following example:
fun main() {
val a = readln().toInt()
val b = readln().toInt()
println(if (a == b) {
"a equal b"
} else if (a > b) {
"a is greater than b"
} else {
"a is less than b"
})
}
In the example above, the if expression is passed directly to the println() function without declaring a variable, and println() prints the result.
Idiom
Prefer using the expression-style if when you need to get results, as it can help avoid potential issues caused by mutable variables or forgotten changes. For example:
val max = if (a > b) a else b // one line
In summary, Kotlin's if expression provides a powerful and flexible way to handle conditional execution of code. By using expression-style if, you can take advantage of its ability to return values and simplify your code. If you know Java, you could map it to a ternary operator:
final String msg = num > 10
? "Number is greater than 10"
: "Number is less than or equal to 10";Using "when" as a more powerful alternative to "if-else-if" chains
Kotlin provides a more powerful and expressive alternative to if-else-if chains called the when expression. The when expression simplifies the process of handling multiple conditions and makes the code more readable.
Here's an example of how to use when:
val number = 5
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
4 -> println("Four")
else -> println("Number is greater than four")
}
In this example, the when expression checks the value of the number variable against different conditions. If the value matches one of the conditions, the corresponding block of code will be executed.
Using "when" as an expression
Similar to the if expression, when can also be used as an expression that returns a value. The value returned by the when expression is the result of the last expression in the matching branch.
val number = 3
val message = when (number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
4 -> "Four"
else -> "Number is greater than four"
}
println(message) // Output: ThreeUsing "when" with ranges and conditions
when expressions can also be used with ranges and more complex conditions. Here's an example:
val number = 15
when {
number < 0 -> println("Negative number")
number in 1..10 -> println("Number between 1 and 10")
number % 2 == 0 -> println("Even number")
else -> println("Odd number greater than 10")
}
In this example, the when expression checks the value of number against different conditions, including ranges and custom conditions.
Conclusion
In conclusion, Kotlin provides powerful constructs like the if and when expressions to handle conditional execution of code. These expressions can return values, making the code more concise and expressive. Using these constructs effectively will help you write more readable and maintainable code in Kotlin.