Line At A Time
Lesson 17: For Loop
For Loop Visit every item in an array, one by one.
1fun main() {
2 val greetingWords = arrayOf("hello", "world", "!")
3 for (word in greetingWords) {
4 println(word)
5 }
6}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
hello
world
!
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 greetingWords = arrayOf("hello", "world", "!")
An array of text values; the items go inside arrayOf(...), each in its own double quotes.
for (word in greetingWords) {
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. Naming the loop variable word (singular) and the array greetingWords makes it read almost like English.
println(word)
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. Runs three times, once per item, and word is different each time.
}
This } closes the for loop. Everything between the loop's { and } is repeated on every trip around the loop.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.