Andrea
Andrea

Reputation: 20493

Scala package objects and Play! 2

I have a Play! 2 application and some functions that are reused across models. I thought to put them inside the models package object, as in the following example

import java.util.Date

package object models {
  case class RichDate(d: Date) {
    def timestamp: Long = d.getTime / 1000
  }

  implicit def enrich(d: Date): RichDate = new RichDate(d)
}

so that everywhere I have a date field in a model I can write myDate.timestamp

This compiles and even works in unit tests. For some reason, though, when I run the actual application, I get an Execution Exception [NoSuchMethodError: models.package$.enrich(Ljava/util/Date;)Lmodels/package$RichDate;]

Is there a reason why the above should not work in a Play! application, while being valid Scala?

Upvotes: 2

Views: 357

Answers (1)

Mark S
Mark S

Reputation: 1453

I've run across this as well and it turned out that the weird behavior was due to package object models already being defined in the framework. This basically makes the package object models off limits to users of the framework. My solution was to put my library pimping in utility objects (such as utils.DateUtils) and just import them when appropriate.

Upvotes: 3

Related Questions