For Loop Addition
Add up every number in an array.
1fun main() {
2 val numbers = intArrayOf(1, 2, 3)
3 var total = 0
4 for (number in numbers) {
5 total += number
6 }
7 println(total)
8}
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
6
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 numbers = intArrayOf(1, 2, 3)- An int array holding the three numbers we want to add up.
var total = 0- var creates a variable whose value CAN change later. The Kotlin habit is: use val unless you know the value must change. total starts at 0 and will collect the running sum. It changes on every trip, so it must be a var, not a val.
for (number in numbers) {- for (item in items) visits each item in turn, one trip around the loop per item, and each time item holds the current value. No counter and no i++: in Kotlin a for loop walks over the items directly.
total += number- += adds the value on the right onto the variable on the left. total += number is a shorter way of writing total = total + number. The loop adds 1, then 2, then 3 onto total: 0+1=1, 1+2=3, 3+3=6.
}- This } closes the for loop. Everything between the loop's { and } is repeated on every trip around the loop.
println(total)- 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. By the time the loop has finished, total is 6.
}- This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.