1
votes

I'm trying to create a way to add days to a LocalDate object in Scala through implicit classes, but I continually get an error either saying "LocalDate is a final class and cannot be extended" or below:

scala:73: could not find implicit value for parameter year: Int

Here's the code I tried using:

 implicit class UVMLocalDate(val me: Int) extends AnyVal{

 implicit def days(implicit year: Int, month: Int, day: Int) {
 LocalDate.of(year,month,me + days)
 }

 }

I'm restricted to having the class behave like so:

(LocalDate.of(2015, 4, 14)) == (LocalDate.of(2015, 4, 12) + 2.days)

Example use:

val dateEx = LocalDate.of(2015, 3, 23) + 2.days
assert(dateEx == LocalDate.of(2015, 3, 25))

Thanks

1
Are you using java.time? In that case, you can't add 2 LocalDates together. It also doesn't provide a Scala + method.Teo Klestrup Röijezon
Also you are taking in 3 implicit Int arguments to your "days" method, implicit arguments are resolved by type so you would always have the same value for all 3 arguments.Angelo Genovese
I can't find much connection between the implicit class pasted and the way you want it to behave.pedrofurla
Please rephrase the question. Providing an example of the code which would use this new days method would be immensely helpful.Angelo Genovese

1 Answers

2
votes

Sounds like you want a mixture of features from scala.concurrent.duration._ and org.joda.time._.

It does not really make sense to add a date to another date and 2.days is not really a date but rather a duration. You could go ahead and re-invent the wheel by defining a new class for it:

class Duration(millis: Long)
object Duration {
  val SecondMillis = 1000
  val MinuteMillis = SecondMillis * 60
  val HourMillis = MinuteMillis * 60
  val DayMillis = HourMillis * 24

  implicit class DurationFromDays(private val underlying: Int) extends AnyVal {
    def days: Duration = new Duration(underlying * DayMillis)
  }
}

However, you could just use the API by scala.concurrent.duration.Duration.

And then you also need to define an implicit class for adding a Duration to a LocalDate.

implicit class LocalDateOps(private val underlying: LocalDate) extends AnyVal {
  def +(duration: Duration): LocalDate = ???
}

However, there are libraries (like joda-time) where the functionality to add a duration to a date is already implemented.