Line At A Time
Lesson 11: AND Operator
AND Operator Combine conditions with && (AND).
1fun main() {
2 val isTrue = true
3 val isFalse = false
4 if (isTrue && isFalse) {
5 println("both are true")
6 } else {
7 println("1 or more is false")
8 }
9}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
1 or more 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 isTrue = true
A Boolean can store only one of two values: true or false, both lowercase.
val isFalse = false
A Boolean can store only one of two values: true or false, both lowercase.
if (isTrue && 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. && means AND: the whole condition is only true if both sides are true. true && false is false, so this block is skipped.
println("both are 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. Skipped: the condition was 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("1 or more 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.
}
This } closes the else block.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.