Conditionals in Kotlin: if and when
Content Index
- if Conditionals
- Returning values/variables in the conditional
- The "Ternary" operator in Kotlin
- Checking if a variable is null: smart casting
- The when block: A Switch on steroids
- Implicit Execution (Break)
- Range and Type Comparisons
- Advanced Features of when
- Use of functions and complex logic
- Mathematical operations:
- Summary
Conditionals are a fundamental element in any programming language, allowing us to perform branches in the code based on a condition established within them. In this entry, we will see how to use the if and when conditionals, the latter being a variant of switch in Kotlin.
if Conditionals
The if() conditional is very similar to the one used in any other programming language like Java, PHP, JavaScript, etc.
val d: Int
val check = true
if (check) {
d = 1
} else {
d = 2
}
println(d)
// 1Returning values/variables in the conditional
In this small example, we compare the variable x to the value returned by the conditional, which can be true or false depending on the value that the variable x has at a given moment (for the example, h would have the value true); to use this structure, we must leave the value we want to return (in this case a boolean) at the end of the conditionals (the if and the else, of course, the conditional can implement any other logic or series of operations, but the return values (those we want to set in the assigned variable) must be established at the end of the conditional).
This is an interesting functionality in Kotlin that allows reducing the number of lines of code when we want to express a hierarchy of conditionals, redundancy in the assignment to final variables, and allows us to have more concise and readable code which translates into a better experience when developing our applications, and of course, we can practically use this scheme with any other structure.
Conditionals in Kotlin follow traditional logic but with a very powerful modern feature: they can return a value. This is especially useful when working with nullability or API requests.
But it has an interesting addition that allows indicating that if the last expression of a conditional is a value, then we can assign that value to a variable; that is:
var x = 5
val h = if (x > 0) {
// other operations
true
} else {
// other operations
false
}If you need to assign a value to a constant (val) based on a condition (such as if a user is authenticated to show their list of courses), you can do it directly. By using val, you ensure that this property does not change during execution, keeping the code clean and safe from the very beginning:
val result = if (userAuthenticated) {
"Course pool"
} else {
"Default value"
}The "Ternary" operator in Kotlin
In Kotlin, the classic ternary operator (condition ? true : false) does not exist, but it is simulated in a very elegant way using if on a single line:
val message = if (isLogged) "Welcome" else "Please log in"Checking if a variable is null: smart casting
A very important point is that apart from the implementations we saw earlier to use the properties of Nullable variables (variables that can be null in Kotlin) through a conditional:
val str: String? = "Kotlin"
if (str != NULL) {
println(str.length)
}Recall that if a variable is declared as Nullable, it means it can be null at any time and therefore we must mandatorily use the operators we used in a previous entry to avoid null references. However, by performing the above verification, we can skip this step of using those operators, since the Kotlin compiler does a "smart cast" on the Nullable variable we are checking, and in this way, we can use any property without the need for these operators.
The when block: A Switch on steroids
Another expression we can use when we have many conditionals is the when expression, which is the equivalent of the switch expression in other programming languages but also enhanced.
The "when" evaluates an object and executes the matching branch. The "else" case acts like the "default" in a traditional switch:
val objecto = "Hello"
when (objeto) {
"1" -> println("It is one")
"Hello" -> println("It is a greeting")
else -> println("No match")
}Implicit Execution (Break)
In Kotlin, "when" has an implicit "break". Once it finds the first match that is true, it executes its code and exits the block. You don't need to write break in every case.
Range and Type Comparisons
We can express values by range:
when (x) {
in 1..9 -> print("x is a positive single-digit integer")
else -> print("x is not a positive single-digit integer")
}We can use functions to indicate the data type of the variable:
when (x) {
is String -> print("x is text")
else -> print("none of the above")
}Advanced Features of when
Using custom functions or functions from an API:
Use of functions and complex logic
You can use the result of a function inside the branches of the "when". Additionally, if you don't pass a parameter to "when", it behaves like a series of if-else if blocks, allowing you to freely place comparison conditions (>, <, !=).
fun add_five(n: Int): Int {
return n + 5
}
fun main() {
val x = 10 // Let's assume x is 10
when (x) {
in 1..9 -> println("x is a single digit")
// This condition is met if x is equal to the result of the function
// For example, if x were 15 and we pass 10 to the function:
add_five(10) -> println("x is 15 (because 10 + 5 = 15)")
!in 10..20 -> println("x is out of range")
else -> println("none of the above")
}
}Indicating if a number is even:
when (x){
x.isEven() -> print("x is even")
else -> print("x is odd")
}Or indicating it is odd, by negating the previous function:
when (x){
!x.isEven() -> print("x is even")
else -> print("x is odd")
}Or using the function to indicate the number is odd:
when (x){
x.isOdd() -> print("x is odd")
else -> print("x is even")
}These last examples use extension functions to define isOdd() and isEven(), which will be the subject of another entry.
Also, as you can see in the previous code, we can use the reserved word else, which works the same as default in other programming languages.
We can choose not to express the value in the when clause and instead express it in each of the cases.
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}Mathematical operations:
when(x) {
10 + 20 -> print("30")
else -> print("Other value")
}Of course, these values can be variables.
We can also use the defined when block to return a value and have it assigned to a variable, just as we did with if earlier:
val r = when(x) {
10 + 20 -> "30"
else -> "Other value"
}We can combine all these options we saw previously as we wish; the idea is to present some of the possible scenarios to have a clearer idea of the operation of this powerful conditional that we can use in Kotlin.
Summary
- if/Else: These can be used as expressions to assign values directly.
- When: This is the replacement for switch. It is cleaner, allows using ranges (in), evaluating functions, and does not require break.
- Safety: Kotlin forces you to respect data types in comparisons, which avoids abstract errors and makes the code more readable.
The next step we're going to look at is how to use functions in Kotlin.
I agree to receive announcements of interest about this Blog.
Conditionals are a fundamental element in any programming language, they allow you to make branches in the code based on a condition established in them. In this post we will see how to use the if and when conditionals in Kotlin.