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:
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
).
fun main() {val i = 1 // or 5if (i < 3) { // i < 3 is used as a condition// will be executed when condition returns trueprintln("Smaller")} else {// will be executed when condition returns falseprintln("Bigger")}// Prints Smaller if i == 1, or Bigger if i == 5}