Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: How to teach jsoniter-scala about zio.prelude.Newtype ? #1124

Open
domdorn opened this issue Feb 28, 2024 · 1 comment
Open

Question: How to teach jsoniter-scala about zio.prelude.Newtype ? #1124

domdorn opened this issue Feb 28, 2024 · 1 comment
Labels

Comments

@domdorn
Copy link

domdorn commented Feb 28, 2024

Hello!

We decided to migrate from

case class RelationTypeId(x: String) extends AnyVal

to

object MyId extends zio.prelude.Newtype[String]

with a

package xxx { 
 type RelationTypeId = RelationTypeId.type
}

Now, I have to create codecs for all these datatypes by hand like

  implicit val relationTypeIdCodec: JsonCodec[RelationTypeId]     = new JsonCodec[RelationTypeId] {
    override def decodeValue(in: JsonReader, default: RelationTypeId): RelationTypeId = RelationTypeId(in.readString(RelationTypeId.unwrap(default)))

    override def encodeValue(x: RelationTypeId, out: JsonWriter): Unit = out.writeVal(RelationTypeId.unwrap(x))

    @SuppressWarnings(Array("AsInstanceOf"))
    override def nullValue: RelationTypeId = null.asInstanceOf[RelationTypeId]

    override def decodeKey(in: JsonReader): RelationTypeId = RelationTypeId(in.readKeyAsString())

    override def encodeKey(x: RelationTypeId, out: JsonWriter): Unit = out.writeVal(RelationTypeId.unwrap(x))
  }

Is there a way I could teach jsoniter-scala how to create the codecs?
I tried creating one like this, but can't get it to compile:

  implicit def newtypeStringCodec[T <: zio.prelude.Newtype[String]]: JsonCodec[T] =
    new JsonCodec[T] {
      override def decodeValue(in: JsonReader, default: T): T = T(in.readString(T.unwrap(default)))

      override def encodeValue(x: T, out: JsonWriter): Unit = out.writeVal(T.unwrap(x))

      @SuppressWarnings(Array("AsInstanceOf"))
      override def nullValue: T = null.asInstanceOf[T]

      override def decodeKey(in: JsonReader): T = T.apply(in.readKeyAsString())

      override def encodeKey(x: T, out: JsonWriter): Unit = out.writeVal(T.unwrap(x))
    }
    ```
@plokhotnyuk
Copy link
Owner

Hi Dominik,

Could you please share a repository or Scastie link that will reproduce your compilation errors?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants