{{announcement.body}}
{{announcement.title}}

Learning Kotlin: the For Loop

DZone 's Guide to

Learning Kotlin: the For Loop

Want to learn more about how to use the For loop in Kotlin? Check out this post to learn more about using the For loop to loop over an array of items in Kotlin.

· Java Zone ·
Free Resource

Kotlin has two loops, while and for. When I started, I was like, "yup, I know those." Except, I didn't. whileworks the way I expected it would, but for is something else.

First, Kotlin does not have a traditional for loop, e.g. for (var i =0;i< max; i++). Thefor loop in Kotlin is closer to the iterator foreach loop in C#.

Introduction

Let's start with the basics. How do I run a loop, say 10 times, where we print out 0, 1, 2, 3, 4, 5, 6, 7, 8, 9?

fun main(args:Array<String>) {
    for(i in 0..9) {
        println(i)
    }
}


In this, we use a ClosedRange (0..9) to state the start and end of the loop. This would be the same as for (var i=0; i< 10; i++).

Now, we want to loop over an array of items, so we can do this in two ways. First, we can use the equivalent of the C# for the iterator/JS for of:

fun main(args:Array<String>) {
    val a = arrayOf("The","Quick","Brown","Fox")
    for(i in a) {
        println(i)
    }
}


And, if we perform the older style of using a normal for loop and using the index, we have:

fun main(args:Array<String>) {
    val a = arrayOf("The","Quick","Brown","Fox")
    for(i in 0 until a.size) {
        val value = a[i]
        println(value)
    }
}


What is awesome about the code above is the range. Rather than having the inclusive lower and inclusive upper bounds of the .. range, we use the keyword until, which gives us an exclusive upper bound.

Kotlin is all about helpers, and last time we looked at destructuring, so it shouldn't be a surprise that we can use that to have BOTH the index and the value in the forloop.

fun main(args:Array<String>) {
    val a = arrayOf("The","Quick","Brown","Fox")
    for((i, value) in a.withIndex()) {
        println("$i is $value")
    }
}


Extras

The for loop has two additional options worth knowing. The first is downTo , which loops from the largest to smallest. This example, in print 4321:

for (i in 4 downTo 1) print(i)


The second is step, which allows you to control how many steps to take when moving to the next item. For this example, we will get 42:

for (i in 4 downTo 1 step 2) print(i


Operator

Adding support for this to our own classes is trivial. We merely need to add the interface Iterator<T> to our class. This adds two methods, fun next():T,which should return the next value in the collection, and fun hasNext():Boolean, which should return true if there is another value available. Let us look at doing this with a class of prime numbers. However, for our example, we will add one condition since there are infinite primes for the top bound so that it eventually ends. This is stored in the maxToHunt variable.

In the code, our next function not only returns the next value, it calculates the NEXT NEXT value, which lets us set if there are more primes left if next is called again.

class PrimeNumbers : Iterator<Int> {
    var currentPrime = 1;
    val maxToHunt = 100;
    var morePrimesToFind = true;

    override fun next():Int {
        val result = this.currentPrime;

        this.currentPrime += 1;
        while(this.currentPrime < this.maxToHunt) {
            var primeFound = true
            for(divisor in this.currentPrime-1 downTo 2) {  
                if (this.currentPrime % divisor == 0) {
                    this.currentPrime += 1
                    primeFound = false
                    break
                }
            }

            if (primeFound) {
                break
            }
        }

        this.morePrimesToFind = this.currentPrime < this.maxToHunt
        return result
    }

    override fun hasNext() = this.morePrimesToFind
}

fun main(args:Array<String>) {
    for (i in PrimeNumbers()) {
        println("$i is prime")
    }
}


Topics:
java ,tutorial ,kotlin ,for ,for loop ,string ,operator ,while

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}