Kotlin loops- For-loop, ForEach, While, Break & Continue

This time, we will cover the basics of the Kotlin- loops. We will see, how to use for-loop, forEach, while, break and continue in our code.
A featured image for category: Kotlin

1. Introduction

Hello dear readers and welcome to my 13th article. In the beginning, I wanted to thank you so much for all the feedback, you’ve provided so far. I am doing my best to provide more and more, better quality content from week to week. I hope, you really enjoy these guides and I would be more than happy if you could share with me your thoughts (for example, by using the contact form). Also, I can now open the secret and announce that video tutorials are coming soon ๐Ÿ™‚

In this article, we will cover the basics of the Kotlin programming language- loops. We will learn, how to use for-loop, forEach, while, break and continue in our code. If you have any prior experience with other programming languages, these concepts may seem trivial for you, but I still believe, that it is worthy to spend some time to remind the core concepts.

2. For Loop

There is no traditional for loop in Kotlin (like you could use in Java or other programming languages). Kotlin’s for loops are pretty similar to Python’s and allow the user to iterate through everything that is iterable (has an iterator()). Let’s see the following examples to get a better understanding of the topic.

2.1. Iterate Through Ranges

Kotlin allows us to easily declare ranges using an operator form (..) of the rangeTo() function. Let’s iterate through such a range:

for (x in 0..5)
  print(x)

As the output, we should see the following:

012345

As you can see, our range contains values from 0 to 5 (inclusive). If we would like to exclude the last value, we should use until:

for (x in 0 until 5) 
  print(x)

Now, only 5 numbers should be printed to the output:

01234

One of the coolest things in ranges is the possibility to control the step:

for (x in 0 until 5 step 2) 
  print(x)

This time, only 0, 2, and 4 will be printed:

024

What happens, if we would like to count downwards? Let’s try to run the following example:

for (x in 5..0) 
  print(x)

Unfortunately, nothing gets printed. The reason for this behavior is that we’ve created the empty range. If we would like this code to work, we need to use downTo:

for (x in 5 downTo 0) 
  print(x)

And this time, everything works as expected:

543210

We can use the step in combination with downTo either:

for (x in 5 downTo 0 step 2) 
  print(x)

Which will generate the following:

531

As the last example, let’s see how to iterate through the range using forEach:

(0..5).forEach { 
  print(it)
}    

After we run the program, we should see the following:

012345

2.2. Iterate Through Arrays

As the next example, let’s see how to iterate through the array. Let’s declare our for-loop to print all values:

val arr = arrayOf(1, 2, 3, 4, 5)
for (x in arr) 
  print(x)

We can achieve the same result using the forEach:

arr.forEach { 
  print(it)
}

2.3. Iterate Through Maps

Kotlin maps are collections that hold pairs of objects (also known as keys and values). Let’s see, how to iterate through a map using for loop first:

// 1st way:
for (x in map)
    println("Key: ${x.key}, value: ${x.value}")

// 2nd way:
for ((key, value) in map)
    println("Key: $key, value: $value")

Both ways will generate the same output. The difference between them is, that in the second case we operate directly on the key and value from the Entry object.

Key: 1, value: One
Key: 2, value: Two
Key: 3, value: Three

Alternatively, we can do the same with forEach:

// 1st way
map.forEach { 
  println("Key: ${it.key}, value: ${it.value}") 
}

// 2nd way
map.forEach { 
  (key, value) -> println("Key: $key, value: $value") 
}

3. While loop

If you have ever seen a while or do-while loop in any other programming language, then you can skip this part. The syntax for a while loop looks as follow:

var a = 0
while (a < 5) {
    print(a)
    ++a
}

var b = 0
do {
    print(b)
    ++b
} while (b < 5) 

The result in both cases will be the same and 5 numbers will be printed to the output.

4. Break & Continue

These two words are nothing new in programming neither and you might already encounter them somewhere. The break statement is used to stop the loop and continue is used to skip the rest of the code in the current iteration of the loop. One of Kotlin’s features is the possibility of labeling a loop and referring to it in order to indicate which loop we would like to affect.

4.1. Continue Statement

Let’s start with the following example of a continue statement:

one@ for (x in 0..5) {
    for (y in 0..1) {
        if ( (x + y) % 2 == 0)
            continue@one
        println("$x - $y")
    }
}

As you can see, we declared that we want to skip the outer loop iteration, not only the inner one. The above code will produce the following output:

1 - 0
3 - 0
5 - 0

As the next example, let’s remove the label and use the simple continue statement:

for (x in 0..5) {
    for (y in 0..1) {
        if ( (x + y) % 2 == 0)
            continue
        println("$x - $y")
    }
}

This time, only the inner loop will be affected, producing the following output:

0 - 1
1 - 0
2 - 1
3 - 0
4 - 1
5 - 0

4.2. Break Statement

As I have mentioned earlier, the break statement is used to stop the loop. Just like a continue, a break might be used with a label:

one@ for (x in 0..5) {
    for (y in 0..1) {
        if ( (x + y) % 2 == 0)
            break@one
        println("$x - $y")
    }
}

What happens if we run the above example? Nothing gets printed– the condition is fulfilled in the first iteration (0+0=0, which is an even number) and we exit the outer loop. If we didn’t use the labels, like here:

for (x in 0..5) {
    for (y in 0..1) {
        if ( (x + y) % 2 == 0)
            break
        println("$x - $y")
    }
}

Then, the result will be the following:

1 - 0
3 - 0
5 - 0

In this scenario, we would exit the inner loop each time the result of the equation would be an even number.

5. Conclusion

I believe that would be all for today’s article. I hope, that I’ve managed to clearly describe the syntax and different types of Kotlin loops and that you will find this article useful.

If you would like to ask any questions or share your point of view, please let me know in the comment section below.

And finally, if you would like to get the source code for this project, please visit this GitHub repository.

Share this:

Related content

2 Responses

  1. I have read so many articles concerning the blogger lovers however this article is genuinely a nice piece of writing, keep it up. Godiva Lowell Stead

Leave a Reply

Your email address will not be published. Required fields are marked *

Newsletter
Image presents 3 ebooks with Java, Spring and Kotlin interview questions.

Never miss any important updates from the Kotlin world and get 3 ebooks!

You may opt out any time. Terms of Use and Privacy Policy