In the previous tutorial we saw how to use control flow statements. In this Kotlin tutorial we will take a look at the different types of looping constructs. If you have ever programmed in a language you will be familiar with most of these.

For Loop

The for loop in kotlin is different from for loops in other languages. In kotlin we use a different syntax in for loop, lets see an example.

As you can see we first created a list of string and then in the for loop we use the in keyword to loop over the list. The for loop will substitute each value of countries in the country variable one-by-one.

Suppose you want the index of the value while you are looping, you can do as following.

We call the withIndex function on the list, now rather than substituting the country variable with just the value in the list, it substitutes the country variable with an object that contains two variables named: index and value, the index is an integer that gives the current position of the list, value contains the item value from the list.

There is one more syntax to get the indexes of the list or array.

In this case we call the indices function on the list. This time the value in the index variable will be an integer value which is the current position in the list.

While Loop

The while loop is the same as in most languages.

Do-While Loop

Similar to the while loop, the do-while loop is also same as in most of the languages.


<< Previous Tutorial “Getting Started with Kotlin – Tutorial 2 – Control Flow”

Gurleen Sethi

Android Developer and enthusiast, believes in developing products and content to help people. Likes to do deep thinking.


Leave a Reply

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

three + five =