Reputation: 313
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
Upvotes: 1
Views: 577
Reputation: 7162
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.
Upvotes: 2