Line At A Time
Lesson 8: Else Statement
Else Statement Run one thing when true, another when false.
1fun main() {
2 val isFalse = false
3 if (isFalse) {
4 println("isFalse is true")
5 } else {
6 println("isFalse is false")
7 }
8}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
isFalse is false
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 isFalse = false
A Boolean can store only one of two values: true or false, both lowercase.
if (isFalse) {
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. Here the condition is false, so the code inside this block is skipped.
println("isFalse is true")
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 never runs, because the condition above is false.
} 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.
println("isFalse is false")
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 is the line that runs, because the if condition was false.
}
This } closes the else block.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.