Line At A Time
Lesson 2: Variable Addition
Variable Addition Add two variables together and print the result.
1fun main() {
2 val five = 5
3 val ten = 10
4 println(five + ten)
5}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
15
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 five = 5
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.
val ten = 10
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. You can create as many variables as you like, as long as each has a different name.
println(five + ten)
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. Kotlin works out five + ten first (5 + 10 = 15) and then prints the answer.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.