2

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?

2
  • This is compilation time error, right? What else do you want? Commented Dec 2, 2015 at 17:28
  • Yes, it happens in compilation time. Commented Dec 2, 2015 at 17:30

1 Answer 1

3

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) } } 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! But just in case, there is no magic. You were telling the compiler "find an implicit for any possible A <: Entity", which is impossible (you might even write new Entity types later on). Now you are passing the responsibility to the caller to "give me an implicit for the type A you are calling me with", which the compiler can figure out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.