Question

I'm just starting my journey with scala. I'm trying to define an implicit conversion that will make it possible to iterate over each day in a period of time in this way:

for (day <- firstDay until lastDay) {
  // a lot of interesting code goes here
}

What I managed to do so far is something like this:

implicit class DateTimeWithUntil(from: DateTime) {
  def until(to: DateTime): Stream[DateTime] =
    from #:: from.plusDays(1)
}

What is the way to implement until method? Is the Stream appropriate for this? Or should it be Iterator or Seq? Or other?

Thanks

Was it helpful?

Solution

I think you are looking for something like this:

import org.joda.time._

implicit class DateTimeOps (startDt: DateTime) {
  def until(endDt: DateTime) = for(dayNo <- 0 until Days.daysBetween(startDt, endDt).getDays) yield(startDt.plusDays(dayNo))
}

for(day <- new DateTime() until new DateTime().plusDays(10)) println (day)

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top