The Programmers Guide To Kotlin - Iterators, Sequences & Ranges
The Programmers Guide To Kotlin - Iterators, Sequences & Ranges
Written by Mike James   
Monday, 29 January 2018
Article Index
The Programmers Guide To Kotlin - Iterators, Sequences & Ranges




What about adding a step function to turn it into a Progression?

This is easy, because all we really need to do is provide a step parameter and an implementation of the step infix operator. The way that this works is fairly simple. If we have a for loop:

for(d in startDay..endDay step 2){

Then the rangeTo function is called with startDay and endDay and this creates a Range object, i.e. a Progression object with a step size of 1. Next the step infix operator is called on the object that the rangeTo function returned i.e. range.step(2) and this has to use the Range object to construct a Progression object with the same start and end dates and a step size as specified.

If we were creating the Progression class "properly" then we would implement it as a class, and the Range class would inherit from it – after all what is a Range but a Progression with step=1.

For simplicity let's just modify the code that we have for Range and turn it into a Progression in all but name.

First we need to update the DataRangeIterator to use a step parameter:

class DateRangeIterator(val start: Date,
                        val endInclusive: Date,
                        val step: Long)
                        : Iterator<Date> {
    private var current = start
    override fun hasNext(): Boolean {
     if (current > endInclusive) return false
     return true
    override fun next(): Date {
     var next = Date(current.getTime())
     current.setTime(current.getTime() +
              step * 24 * 60 * 60 * 1000)
     return next

Notice that step is specified in days.

With this change we need to modify the DataRange class to set the new step parameter:

class DateRange(override val start: Date,
                override val endInclusive: Date,
                val step: Long = 1)
                      : Iterable<Date>,
ClosedRange<Date> {
    override fun iterator(): Iterator<Date> {
        return DateRangeIterator(start,
                     endInclusive, step)

Notice that the default value of 1 for the step parameter means that this can be called to create a range i.e. without a step argument at all. The rangeTo function stays the same:

operator fun Date.rangeTo(other: Date) =
                          DateRange(this, other)

where the DataRange object really is treated as a DateRange object i.e. step=1.

We also need a step infix operator function:

infix fun DateRange.step(step: Long)
                         : DateRange {
  return DateRange(

This is called on the DateRange object that the rangeTo creates, and it uses it to construct a new DateRange object but this time with a step size that is something other than one. In a more general setting this would create an instance of a different class to DateRange i.e. DateProgression, but there is no real difference in implementation.

Now we can write:

val dfm = SimpleDateFormat("yyyy-MM-dd")
    val startDay = dfm.parse("2017-01-01")
    val endDay = dfm.parse("2017-01-07")
    for (d in startDay..endDay step 2) {

which produces

Sun Jan 01 00:00:00 GMT 2017
Tue Jan 03 00:00:00 GMT 2017
Thu Jan 05 00:00:00 GMT 2017
Sat Jan 07 00:00:00 GMT 2017

There are lots of things missing from this implementation of a Progression object – there are no checks for a positive step size, and there are lots of missing methods – downTo, reversed and so on – but it does illustrate how flexible the implementation of the Kotlin for loop can be.

Chapter Summary

(italicized text refers to material not included in this  extract)

  • Collections store objects as references and make use of generics to work with any type of object.

  • The base class is Collection but List and MutableList are the best examples of how collections work.

  • Collections generally have factory methods such as collectionOf to create initialized instances. Some also make use of their constructor and an initialization function.

  • Kotlin collections come in mutable and immutable versions. The immutable version is more like a read-only type than a true immutable data structure.

  • The other core collection types are Maps and Sets.

  • A Map stores key value pairs.

  • A Set stores objects in no particular order without duplicates.

  • An iterator is an object with at least two methods – next which returns the next object and hasNext which is true if there is a next object.

  • Iterators are used to implement for loops and other basic Kotlin constructs and you can implement custom iterators.

  • Sequences are lazy iterators designed to make functional programming in Kotlin more efficient.

  • A Range is a special sort of iterator that has a start and stop value.

  • A Progression is a Range with a step size.

  • You can implement custom Ranges and Progressions.


This article is an extract from: 

Programmer's Guide To Kotlin

Now Available as a Print Book


You can buy it from:

USA and World




Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy 
    Extract  Type and its problems
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
                                               (Coming soon!)
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
    Extract  Data Classes 
  13. Exceptions, Annotations & Reflection
    Extract Annotation & Reflection **NEW!**
  14. Working with Java

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, FacebookGoogle+ or Linkedin.



Linux Apps On Chromebooks

Sometimes you have got to think that we are working in the maddest of subjects. Chromebooks are about to get the ability to run Linux apps. The fact that ChromeOS is Linux is the part that is mad.

AI Creates Flintstones Cartoons From A Description

As long as you know the Flintstones, and if you don't you've been under a (Bed)rock for too long, then "Fred is talking to Barney in the lounge" will cause you to imagine the scene. Now an AI system c [ ... ]

More News



or email your comment to:


Last Updated ( Monday, 29 January 2018 )

RSS feed of all content
I Programmer - full contents
Copyright © 2018 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.