Kotlin – 7 – Kotlin Control Flow (if, else, when)

Control flow statements in Kotlin, such as if, else, and when, enable you to make decisions and perform conditional actions in your programs. They provide the means to control the flow of code execution based on specified conditions. In this guide, we’ll explore how to use if, else, and when statements in Kotlin and provide examples to illustrate their usage.

The if Statement

The if statement in Kotlin is used to execute a block of code conditionally. It evaluates a boolean expression, and if the expression is true, it executes the code within the if block; otherwise, it continues to the next statement after the if block. The basic syntax is as follows:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Here’s an example:

val age = 18

if (age >= 18) {
    println("You can vote.")
} else {
    println("You cannot vote.")
}

In this example, the if statement checks if age is greater than or equal to 18. If the condition is true, it prints “You can vote.”; otherwise, it prints “You cannot vote.”

The else Clause

The else clause is optional in Kotlin’s if statement. When included, it allows you to specify code that should execute if the condition in the if statement is false. You can have multiple else if blocks to handle multiple conditions. Here’s an example with else if:

val num = 5

if (num > 0) {
    println("Positive")
} else if (num < 0) {
    println("Negative")
} else {
    println("Zero")
}

In this example, the code checks whether num is positive, negative, or zero and prints the corresponding message.

The when Expression (Replacement for Switch)

The when expression in Kotlin serves as a replacement for the traditional switch statement in other languages. It allows you to evaluate multiple conditions and execute code based on the first matching condition. The basic syntax is as follows:

when (expression) {
    value1 -> {
        // Code to execute if expression equals value1
    }
    value2 -> {
        // Code to execute if expression equals value2
    }
    else -> {
        // Code to execute if none of the above conditions are met
    }
}

Here’s an example:

val day = 2
val dayOfWeek = when (day) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    4 -> "Thursday"
    5 -> "Friday"
    else -> "Weekend"
}

In this example, dayOfWeek is assigned a value based on the day variable. If day is 2, it sets dayOfWeek to “Tuesday”; if it’s 6 or any other value, it sets dayOfWeek to “Weekend.”

Ranges in when Expressions

when expressions are often used with ranges to evaluate conditions based on a range of values. Here’s an example:

val score = 85
val grade = when (score) {
    in 90..100 -> "A"
    in 80 until 90 -> "B"
    in 70 until 80 -> "C"
    in 60 until 70 -> "D"
    else -> "F"
}

In this example, grade is determined based on the range in which score falls. If score is between 90 and 100, it gets an “A” grade, and so on.

The is Operator in when Expressions

The is operator in a when expression is used to check the type of an object. It allows you to execute code based on the type of the object. Here’s an example:

val value: Any = 42

when (value) {
    is String -> println("It's a string")
    is Int -> println("It's an integer")
    else -> println("It's something else")
}

In this example, the code checks whether value is a String or an Int and prints the corresponding message.

Command and Example

Here’s an example demonstrating the use of if, else, and when in Kotlin:

fun main() {
val num = 7

if (num % 2 == 0) {
println(“$num is even.”)
} else {
println(“$num is odd.”)
}

val day = 4
val dayOfWeek = when (day) {
1 -> “Monday”
2 -> “Tuesday”
3 -> “Wednesday”
4 -> “Thursday”
5 -> “Friday”
else -> “Weekend”
}

println(“Today is $dayOfWeek”)

val value: Any = 3.14
when (value) {
is String -> println(“It’s a string”)
is Int -> println(“It’s an integer”)
else -> println(“It’s something else”)
}
}

In this example, we use if to check if a number is even or odd. We also use when to determine the day of the week based on a numeric value and to check the type of a variable (value) using the is operator.

Control flow statements like if, else, and when are essential for making decisions in your Kotlin programs. They allow you to control the flow of execution based on various conditions and make your code more dynamic and responsive to different situations. Understanding how to use these statements effectively is a key skill for Kotlin developers.