Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit numeric widening for LocalDate.now().plusMonths(m)

I have this code in an implicit class like this:

object TenorOperations {
  implicit class TenorOperations(thiss: Tenor) {

    def toDate: LocalDate = thiss match {
      case Day(d) => LocalDate.now().plusDays(d)
      case Month(m) => LocalDate.now().plusMonths(m)
      case Year(y) => LocalDate.now().plusYears(y)
      case errorDate => throw new Exception("Unexpected date: "+errorDate)
    }

  }
}

It just won't compile in IDEA.

Error:(14, 47) implicit numeric widening
      case Day(d) => LocalDate.now().plusDays(d)
                                              ^
Error:(15, 51) implicit numeric widening
      case Month(m) => LocalDate.now().plusMonths(m)
                                                  ^
Error:(16, 49) implicit numeric widening
      case Year(y) => LocalDate.now().plusYears(y)
                                                ^

This used to work. How can I fix it?

like image 988
Adrian Avatar asked Jan 02 '26 03:01

Adrian


2 Answers

It seems you are using java.time.LocalDate, where LocalDate.plusDays takes a Long, not an Int. Normally this will compile perfectly well, unless you both 1) turn on -Ywarn-numeric-widen to tell Scala compiler to warn you when widening conversions happen; 2) turn on -Xfatal-warnings to make warnings into errors.

You can write LocalDate.now().plusDays(d.toLong) (etc) to make the conversions explicit.

like image 83
Alexey Romanov Avatar answered Jan 04 '26 13:01

Alexey Romanov


I am not sure about why it happens, but you can try LocalDate.now().plusMonths(Period.months(m)) (same for days and years).

like image 20
John K Avatar answered Jan 04 '26 12:01

John K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!