If Statement
Only run code when a condition is true.
1fun main() {
2 val isTrue = true
3 if (isTrue) {
4 println("isTrue is true")
5 }
6}
$ 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.
if (isTrue) {- 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 simply the variable isTrue, which is true, so the code inside 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 } closes the if block.
}- This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.