Reader small image

You're reading from  Kotlin Design Patterns and Best Practices - Second Edition

Product typeBook
Published inJan 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801815727
Edition2nd Edition
Languages
Right arrow
Author (1)
Alexey Soshin
Alexey Soshin
author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin

Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Second Edition
Published in: Jan 2022Publisher: PacktISBN-13: 9781801815727
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin