Search code examples
scalareflectionargonaut

Do we need to avoid reflection when design scala libraries?


Take argonaut for example, in some of our projects, when there is the need to handle JSON, people will use argonaut for that, and hardcoding the fields, like:

implicit def AddressCodecJson: CodecJson[Address] =
    casecodec3(Address.apply, Address.unapply)("street", "number", "post_code")

If there is a big case class, the list will be very long:

implicit def AddressCodecJson: CodecJson[Address] =
    casecodec12(Address.apply, Address.unapply)("street", "number", "post_code", "...", "...", "...", "...", "...", "...", "...", "...", "...")

My question is why do we need to hardcode them, rathar than get the field by reflection?

Is there any technical problem, or people just don't like using reflection when design Scala libraries?


Solution

  • I am not very clear whether you are trying to parse the json generically. I am assuming that you want to parse any json generically. If that is the case, instead of creting the implicit conversion for each of the case classes, you can use json4s to do that. In that case, you do not need to provide the implcit conversion for each class. We are using it extensively in our project. You only need to give implicit converter for each types (for eg: how to covert java.sql.timestamp, java.sql.Date, Joda-Time etc).

    Probably, this link might help you.