Skip to content

Instantly share code, notes, and snippets.

@igaozp
Created December 25, 2017 10:10
Show Gist options
  • Select an option

  • Save igaozp/ec92bb28e46105b0c8e403282d314863 to your computer and use it in GitHub Desktop.

Select an option

Save igaozp/ec92bb28e46105b0c8e403282d314863 to your computer and use it in GitHub Desktop.
Kotlin 自定义 Iterator
class DateRange(val start: MyDate, val end: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> = DateIterator(start, end)
}
class DateIterator(val start: MyDate, val end: MyDate) : Iterator<MyDate> {
var hasNext = start <= end
var next = if (hasNext) start else end
override fun hasNext(): Boolean = hasNext
override fun next(): MyDate {
val result = next
next = next.nextDay()
hasNext = next <= end
return result
}
}
fun iterateOverDateRange(firstDate: MyDate, secondDate: MyDate, handler: (MyDate) -> Unit) {
for (date in firstDate..secondDate) {
handler(date)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment