Range expression: iterating between two LocalDate objects


I'm just wondering if there's a way to iterate between two java.time.LocalDate objects, one day at a time, by using Range expressions like this:

for(x in LocalDate.of(2016, Month.JANUARY, 1)..LocalDate.of(2016, Month.JANUARY, 7)) { .. }

I've tried to declare an extension function to add an iterator() function to java.time.LocalDate but it didn't work.


Fixed. I've just added the following function...

operator fun ClosedRange<LocalDate>.iterator() : Iterator<LocalDate>{
    return object: Iterator<LocalDate> {
        private var next = this@iterator.start
        private val finalElement = this@iterator.endInclusive
        private var hasNext = !next.isAfter(this@iterator.endInclusive)
 override fun hasNext(): Boolean = hasNext

  override fun next(): LocalDate {
           val value = next
           if(value == finalElement) {
           hasNext = false
           else {
           next = next.plusDays(1)
           return value



Since Progression<T> is deprecated, how could I switch to another iterator (ie. one that iterates over weeks)?


No one stops you from implementing your own LocalDateProgression : Iterable<LocalDate> and providing extension function step for ClosedRange<LocalDate> returning that progression:

fun ClosedRange<LocalDate>.step(step: TemporalAmount): LocalDateProgression = ...