Iltotore / iron

Strong type constraints for Scala
https://iltotore.github.io/iron/docs/
Apache License 2.0
427 stars 37 forks source link

Make zio-json derive work with opaque types #195

Closed sergeda closed 6 months ago

sergeda commented 7 months ago

Is your feature request related to a problem? Please describe. This code fails during compilation

import io.github.iltotore.iron.*
import io.github.iltotore.iron.constraint.string.*
import io.github.iltotore.iron.zioJson.given
import zio.json.JsonCodec
import zio.json.DeriveJsonCodec

opaque type PhoneNumber = String :| Match["^[+]?[0-9]{10,13}$"]
object PhoneNumber extends RefinedTypeOps[String, Match["^[+]?[0-9]{10,13}$"], PhoneNumber]:
    given JsonCodec[PhoneNumber] = DeriveJsonCodec.gen

Error:

[error] 11 |    given JsonCodec[PhoneNumber] = DeriveJsonCodec.gen
[error]    |                                                      ^
[error]    |No given instance of type deriving.Mirror.Of[
[error]    |  io.github.iltotore.iron.IronType[String,
[error]    |    io.github.iltotore.iron.constraint.string.Match[
[error]    |      ("^[+]?[0-9]{10,13}$" : String)]
[error]    |  ]
[error]    |] was found for parameter mirror of method gen in object DeriveJsonCodec. Failed to synthesize an instance of type deriving.Mirror.Of[
[error]    |  io.github.iltotore.iron.IronType[String,
[error]    |    io.github.iltotore.iron.constraint.string.Match[
[error]    |      ("^[+]?[0-9]{10,13}$" : String)]
[error]    |  ]
[error]    |]:
[error]    |    * class String is not a generic product because it is not a case class
[error]    |    * class String is not a generic sum because it is not a sealed class

Describe the solution you'd like It would be great to be able to generate codecs for opaque types

Describe alternatives you've considered For now I'll create instances manually

Iltotore commented 7 months ago

You don't need to use DeriveJsonCodec.gen. It is already automatically derived as long as you have io.github.iltotore.iron.zioJson.given imported.

Iltotore commented 7 months ago

@sergeda do you still have trouble getting a JsonCodec for your opaque type?

Iltotore commented 6 months ago

Closing due to inactivity. Feel free to open a new issue or discussion if you still encounter this problem or have another issue.