Loops
Now, let's discuss another typical control structure – a loop. Loops are a very natural construct for most developers. Without loops, it would be tough to repeat the same code block more than once (although we will discuss how to do that without loops in later chapters).
for-each loop
Probably the most helpful type of a loop in Kotlin is a for
-each
loop. This loop can iterate over strings, data structures, and basically everything that has an iterator. We'll learn more about iterators in Chapter 4, Getting Familiar with Behavioral Patterns, so for now, let's demonstrate their use on a simple string:
for (c in "Word") { println(c) }
This will print the following:
>W >o >r >d
The for
-each
loop works on all the types of data structures we already discussed as well, that is, lists, sets, and maps. Let's take a list as an example:
val jokers = listOf("Heath Ledger", "Joaquin Phoenix", "Jack Nicholson") for (j in jokers) { println(j) }
We'll get the following output:
> Heath Ledger > Joaquin Phoenix > Jack Nicholson
You'll see this loop many more times in this book, as it's very useful.
The for loop
While in some languages for
-each
and for
loops are two completely different constructs, in Kotlin a for
loop is simply a for
-each
loop over a range.
To understand it better, let's look at a for
loop that prints all the single-digit numbers:
for (i in 0..9) { println(i) }
This doesn't look anything like a Java for
loop and may remind you more of Python. The two dots are called a range operator.
If you run this code, you will notice that this loop is inclusive. It prints all the numbers, including 9
. This is similar to the following Java code:
for (int i = 0; i <= 9; i++)
If you want your range to be exclusive and not to include the last element, you can use the until
function:
for (i in 0 until 10) { println("for until $i") // Same output as the previous loop }
If you'd like to print the numbers in reverse order, you can use the downTo
function:
for (i in 9 downTo 0) { println("for downTo $i") // 9, 8, 7... }
It may seem confusing that until
and downTo
are called functions, although they look more like operators. This is another interesting Kotlin feature called infix call, which will be discussed later.
The while loop
There are no changes to the while
loop functionality compared to some other languages, so we'll cover them very briefly:
var x = 0 while (x < 10) { x++ println("while $x") }
This will print numbers from 1
to 10
. Note that we are forced to define x
as var
. The lesser-used do while
loop is also present in the language:
var x = 5 do { println("do while $x") x-- } while (x > 0)
Most probably, you won't be using the while
loop and especially the do while
loop much in Kotlin. In the following chapters, we'll discuss much more idiomatic ways to do this.