The Programmers Guide To Kotlin - Iterators, Sequences & Ranges |
Written by Mike James | ||||||
Monday, 29 January 2018 | ||||||
Page 2 of 2
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:
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:
Notice that step is specified in days. With this change we need to modify the DataRange class to set the new step parameter:
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:
where the DataRange object really is treated as a DateRange object i.e. step=1. We also need a step infix operator function:
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:
which produces
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)
This article is an extract from: Programmer's Guide To Kotlin Third Edition
You can buy it from: Amazon Contents
<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.
Comments
or email your comment to: comments@i-programmer.info
|
||||||
Last Updated ( Monday, 29 January 2018 ) |