CustardBun
CustardBun

Reputation: 3867

Scala: Imported scala object with implicits not working for providing Read or Write format (play json)

I have some scala code that requires the use of implicits for serializing and deserializing json.

We previously had something that worked by putting these implicit statements (simplified with dummies):

  (in some class SomeClass1)

  implicit val some1format = Json.format[SomeItem1]
  implicit val some2format = Json.format[SomeItem2]
  ...

All as class-level variables. Any method within the class was then able to convert from Json just fine.

However, we are trying to move the implicit definitions of these formats to a separate object.

So we created an object (for example: SomeFormatters), which only contains these implicits:

object SomeFormatters {
   implicit val some1format = Json.format[SomeItem1]
   implicit val some2format = Json.format[SomeItem2]
}

When I try to import this object into SomeClass1, I get a compilation error saying that no deserializer was found for SomeItem1 or SomeItem2, even though I am importing SomeFormatters. (The IDE says the import of SomeFormatters is unused though, so I already knew something was off.)

What's the proper way to get SomeClass1 to know about the implicit definitions in SomeFormatters?

Upvotes: 0

Views: 60

Answers (1)

CustardBun
CustardBun

Reputation: 3867

The issue was that there were no type annotations for implicit values -

Instead of:

implicit val some1format = Json.format[SomeItem1]

I needed to put:

implicit val some1format: Format[SomeItem1] = Json.format[SomeItem1]

Upvotes: 1

Related Questions