Course Content
KOTLIN Tutorial
About Lesson

Conditional Statements (if, else if, else)

Kotlin, a modern programming language, offers robust support for conditional statements, making it easier for developers to control the flow of their code. In this post, we’ll delve into the world of conditional statements in Kotlin, specifically focusing on if, else if, and else constructs.

The Basics: if the Statement

The if statement in Kotlin is fundamental for making decisions in your code. It evaluates a boolean expression and executes a block of code if the expression is true. Let’s take a look at a simple example:

val x = 10

if (x > 5) {
println("x is greater than 5")
}

In this example, the code inside the curly braces will be executed because the condition (x > 5) is true.

The else if Clause

When you need to evaluate multiple conditions, the else if clause comes into play. It allows you to check additional conditions if the initial if statement evaluates to false. Here’s an example:

val y = 7

if (y > 10) {
println("y is greater than 10")
} else if (y > 5) {
println("y is greater than 5 but not greater than 10")
} else {
println("y is 5 or less")
}

In this scenario, the second condition (y > 5) is true, so the corresponding block of code will be executed.

The else Statement

The else statement provides a default block of code to execute when none of the preceding conditions are true. It is not mandatory, but it ensures that something happens even if all previous conditions fail. Consider the following example:

val z = 3

if (z > 5) {
println("z is greater than 5")
} else {
println("z is 5 or less")
}

In this case, since the condition (z > 5) is false, the code inside the else the block will be executed.

Nested Conditional Statements

Kotlin supports nested conditional statements, allowing you to create more complex decision-making structures. However, it’s crucial to maintain code readability and avoid excessive nesting, which can lead to confusion.