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
Progressions

cover

 

 

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){
        println(d)
    }

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.start,this.endInclusive,step)
}

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) {
        println(d)
    }

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 Third Edition

kotlin3e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object ***NEW!
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing
  16. Compose Multiplatform
        Extract: Compose Layout 

<ASIN:B0D8H4N8SK>

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, Facebook or Linkedin.

 

Banner


Uno Announces Platform Studio
19/11/2024

Uno has announced Uno Platform Studio, a suite of productivity tools featuring Hot Design, which they describe as a next-generation Visual Designer for .NET cross-platform apps.



TestSprite Announces End-to-End QA Tool
14/11/2024

TestSprite has announced an early access beta program for its end-to-end QA tool, along with $1.5 million pre-seed funding aimed at accelerating product development, expanding the team, and scaling op [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Monday, 29 January 2018 )