...

/

The if Statement

The if Statement

Learn about if-else expressions to implement conditional control over the execution of a chunk of code.

Conditional statements in various languages

Most conditional statements, like the if condition or the while loop, look the same in Kotlin, Java, C++, JavaScript, and most other modern languages. For instance, the if statement is indistinguishable in all these languages:

Press + to interact
if (predicate) {
// body
}

However, the if condition in Kotlin is more powerful and has capabilities that Kotlin’s predecessors don’t support. We assume that you have general experience in programming, so we will concentrate on the differences that Kotlin has introduced compared to other programming languages.

Basic if statement

Let’s start with the aforementioned if statement. It executes its body when its condition is satisfied (returns true). We can additionally add the else block, which is executed when the condition is not satisfied (returns false).

Press + to interact
fun main() {
val i = 1 // or 5
if (i < 3) { // i < 3 is used as a condition
// will be executed when condition returns true
println("Smaller")
} else {
// will be executed when condition returns false
println("Bigger")
}
// Prints Smaller if i == 1, or Bigger if i == 5
}

The if-else expression

...