Else If Statement
Check several conditions, one after another.
1fun main() {
2 val two = 2
3 if (two == 1) {
4 println("Two = 1")
5 } else if (two == 2) {
6 println("Two = 2")
7 } else {
8 println("Two != 1 or 2")
9 }
10}
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
Two = 2
Every line, explained
fun main() {- Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
val two = 2- val creates a read-only variable: a named box whose value is set once and then never changes. Kotlin people reach for val by default, and only switch to var when a value truly needs to change. Notice there is no type word like Int: Kotlin sees the value and works out the type for you. This is called type inference.
if (two == 1) {- if checks the condition inside its round brackets. If the condition is true, Kotlin runs the code between { and }. If it is false, Kotlin skips that code completely. == compares two values and asks "are these equal?". Be careful: a single = stores a value, a double == compares. Here 2 == 1 is false, so this block is skipped.
println("Two = 1")- println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Skipped: two is not 1.
} else if (two == 2) {- } else if (...) { adds another check that is only tried when the condition above it was false. Kotlin tests each condition from top to bottom and runs the first block whose condition is true, skipping the rest. Here 2 == 2 is true, so this block runs.
println("Two = 2")- println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. This line runs.
} else {- } else { attaches an "otherwise" branch to the if above. When the if condition is false, the code inside the else block runs instead. Exactly one of the two blocks runs, never both. This else only runs when every check above it failed.
println("Two != 1 or 2")- println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Skipped: the else if above already matched.
}- This } closes the else block.
}- This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.