DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Learning Kotlin: the For Loop

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.

Robert Maclean user avatar by
Robert Maclean
·
Aug. 20, 18 · Tutorial
Like (6)
Save
Tweet
Share
8.74K Views

Join the DZone community and get the full member experience.

Join For Free

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")
    }
}


Kotlin (programming language)

Published at DZone with permission of Robert Maclean, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top 5 PHP REST API Frameworks
  • Kubernetes vs Docker: Differences Explained
  • Implementing Adaptive Concurrency Limits
  • The Changing Face of ETL

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: