The Programmers Guide To Kotlin- Iterators & Sequences |
Written by Mike James | |||
Wednesday, 24 August 2022 | |||
Page 2 of 2
Ranges & ProgressionsKotlin provides two data types that make it easier to write for loops – the Range and the Progression. Roughly speaking, Range allows you to write things like: for(i in 1..10) and a Progression is a range for which you can specify a step size, for example: for(i in 1..10 step 2) As already explained in connection with the for loop, ranges and progressions integrate into the for using the rangeTo function as an operator .. and the step function. It isn't difficult to create your own ranges and progressions. As an example let's create a range that works for dates. In Java there are far too many date classes in use at the moment, so for simplicity we will use the original Date class, despite most of its methods being deprecated rather than LocalDate, which is its successor. To use this in a Kotlin project you need to add: import java.util.* To create a date range class we need to implement a class, DateRange, that implements the Iterable interface, and the ClosedRange interface which has the endInclusive property: class DateRange(override val start: Date, override val endInclusive:Date):Iterable<Date>,ClosedRange<Date> We need to add the override modifier to the constructor because the properties created by the primary constructor are hiding properties inherited from ClosedRange. We also have to implement iterator which returns a suitable iterator for the range: class DateRange(override val start: Date, override val endInclusive:Date):Iterable<Date>, where DateRangeIterator is the iterator we have yet to implement. DateRangeIterator inherits from Iterator and ClosedRange. We only need to override the iterator's next and hasNext methods and provide implementations of the ClosedRange start and endInclusive properties: class DateRangeIterator(val start: Date, val endInclusive: Date): Iterator<Date> { Notice that as Date is an object we can't just use: var next=current because next and current would both reference the same object and changes made to current would also change next. To keep the values separate, we have to create a new instance with the same values – i.e. we have to clone current. To make the .. operator work we also need to define a suitable rangeTo function: operator fun Date.rangeTo(other: Date) = With this all defined, all that remains is to use the new range class and it is worth listing the complete program: import java.text.SimpleDateFormat import java.util.* fun main() { val dfm = SimpleDateFormat("yyyy-MM-dd") val startDay = dfm.parse("2021-01-01") val endDay = dfm.parse("2021-01-07") for (d in startDay..endDay) { println(d) } } class DateRange( override val start: Date, override val endInclusive: Date): Iterable<Date>, ClosedRange<Date> { override fun iterator(): Iterator<Date> { return DateRangeIterator(start, endInclusive) } } class DateRangeIterator(val start: Date, which prints: Fri Jan 01 00:00:00 GMT 2021 Sat Jan 02 00:00:00 GMT 2021 Sun Jan 03 00:00:00 GMT 2021 Mon Jan 04 00:00:00 GMT 2021 Tue Jan 05 00:00:00 GMT 2021 Wed Jan 06 00:00:00 GMT 2021 Thu Jan 07 00:00:00 GMT 2021 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) 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, Notice that the default value of one for the step parameter means that this can be called to crete a range without a step argument at all. The rangeTo function stays the same: operator fun Date.rangeTo(other: Date) = where the DataRange object still has a step size of one. It is not until we define the step infix operator that it is modified to have a different step size. The step infix operator function is: 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 is used 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 more appropriate class, a DateProgression say, but there is no real difference in implementation from the poorly named DateRange. Now we can write the main program as: import java.text.SimpleDateFormat import java.util.* fun main() { val dfm = SimpleDateFormat("yyyy-MM-dd") val startDay = dfm.parse("2021-01-01") val endDay = dfm.parse("2021-01-07") for (d in startDay..endDay step 2) { println(d) } } class DateRange( override val start: Date, override val endInclusive: Date, val step: Long = 1) : which produces Fri Jan 01 00:00:00 GMT 2021 Sun Jan 03 00:00:00 GMT 2021 Tue Jan 05 00:00:00 GMT 2021 Thu Jan 07 00:00:00 GMT 2021 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. Summary
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 ( Wednesday, 24 August 2022 ) |