Kotlin supports both for
and while
loops.
while
loops work the way that you are used to:
for
loops, however, work a bit differently.
The familiar Java for
loop syntax is not valid Kotlin:
Instead, all Kotlin for
loops work more like the Java enhanched foreach
loop:
In Kotlin we can do something very similar:
But what do we do if we want a numeric loop? We use something called a range:
One nice thing about Kotlin ranges is that they are just objects that can be saved to variables and passed around like any other variable.
Kotlin has syntax for creating ranges that follow a variety of conventions, including up, down, and with different step sizes.
As you can see in the example above, a progression is a generalization of a range.
Anyway—don’t get too attached to Kotlin’s ranges and loops. We’re not going to use them much, since Kotlin provides excellent support for working with data in collections using map-reduce-filter programming patterns.