Coding for All
Lesson 12: Statements and Operators
Statements and Operators Mix &&, == and else if in one program.
1fun main() {
2 val isTrue = true
3 val six = 6
4 if (isTrue && six == 5) {
5 println("isTrue, six = 5")
6 } else if (isTrue) {
7 println("isTrue is true")
8 } else {
9 println("None of the above")
10 }
11}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
isTrue is true
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 isTrue = true
A Boolean can store only one of two values: true or false, both lowercase.
val six = 6
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 (isTrue && six == 5) {
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. Kotlin checks six == 5 first (false, six is 6), then true && false, which is false, so this block is skipped.
println("isTrue, six = 5")
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.
} else if (isTrue) {
} 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. isTrue is true, so this block runs.
println("isTrue 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 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.
println("None of the above")
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: a branch 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 }.