rocketman
rocketman

Reputation: 43

How to finish implicit class

I am trying to write an implicit class that adds days to a date.

I know that I need two implicit classes. One for LocalDate and one for int.

However, I am stuck on how to finish these methods.

implicit class RichLocalDate(d:LocalDate) {
  def +(day: LocalDate):Path = ???
}

implicit class RichInt(n:Int){
  def jan():LocalDate = LocalDate.of(2016,1,n)

  def feb():LocalDate = LocalDate.of(2016,2,n)

  def mar():LocalDate = LocalDate.of(2016,3,n)
  ....
  ???
}
}

Upvotes: 0

Views: 65

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170745

It makes no sense to add two LocalDates in the first place (i.e. your def +(day: LocalDate):Path method). What do you want to be the result of January 1st 2016 + January 1st 2016: February 2nd 4032? You most likely want +(amount: TemporalAmount) instead (see https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAmount.html), which just needs to call plus method.

Upvotes: 1

Henrique Goulart
Henrique Goulart

Reputation: 1855

Sample:

object Pimpeds {
  implicit class PimpedLocalDate[LocalDate](date: LocalDate) {
    def +(days: Int) = date.plusDays(days)
  }
}

When you need it:

import Pimpeds._

val myDate: LocalDate = ...
myDate.+(2)

Upvotes: 2

Related Questions