Quarktum
Quarktum

Reputation: 709

Implicit val in companion object

I am wondering if there is a way to ensure that the companion object has the implicit Json formatter of the class it is accompanying:

trait Entity {
  val id: Int
}

case class Foo(id: Int) extends Entity

object Foo {
  implicit val jsonFormatter = Json.format[Foo]
}

For example:

trait DAO[A <: Entity] {
  def get[A](id: Int) = {
    val docs: JsValue = ???
    Json.fromJson[A](docs)
  }
}

In this case, when it tries to transform the json to the case class, it will not found the implicit transformer. Any ideas to solve this?

Upvotes: 2

Views: 826

Answers (1)

Daniel Langdon
Daniel Langdon

Reputation: 5999

Well, you already have a compiler error if the implicit is not found and it does not get much better than that. But if you are having difficulties using the formatter there, since you are doing so for every possible Entity type:

trait DAO[A <: Entity] {
  def get[A](id: Int) = {
    val docs: JsValue = ???
    Json.fromJson[A](docs)
  }
}

You might want to define it so that the implicit is automatically found for the actual A class:

trait DAO[A <: Entity] {
  def get[A](id: Int)(implicit formatter: JsFormatter[A]) = {
    val docs: JsValue = // Use your formatter here instead of ???
    Json.fromJson[A](docs)
  }
}

Upvotes: 3

Related Questions