zio-json icon indicating copy to clipboard operation
zio-json copied to clipboard

encoding decoding classes with type parameters (scala 2.x) fail compilation

Open artur-jablonski opened this issue 2 years ago • 2 comments

Given this case classes:

@jsonDerive
case class A[T](key1: Int, key2: T)

@jsonDerive
case class B(
    key1: Int,
    key2: Int,
    key3: Int,
  )

this compiles and works fine:

val a: A[B] = A(1, B(1, 2, 3))
a.toJson.fromJson[A[B]]

This however fails to compile:

val a: A[B] = A(1, B(1, 2, 3))

  def foo[T](arg: A[T]) = {
    arg.toJson.fromJson[A[T]]  //compilation error here
  }

  foo(a)

with the following error message

could not find implicit value for parameter encoder: zio.json.JsonEncoder[A[T]]
    arg.toJson.fromJson[A[T]]

I understand this is because at compilation time you can't tell if T has encoder....

Is there a way to have such generic code working with some custom encoders/decoders? How would I go about it?

artur-jablonski avatar Jul 28 '22 13:07 artur-jablonski

@artur-jablonski Have you tried if def foo[T: JsonEncoder](arg: A[T]) works for your case?

plokhotnyuk avatar Jul 28 '22 13:07 plokhotnyuk

This fails to compile with the same error message as before

 def foo[T: JsonEncoder](arg: A[T]) = {
    arg.toJson.fromJson[A[T]]
  }
could not find implicit value for parameter encoder: zio.json.JsonEncoder[A[T]]
    arg.toJson.fromJson[A[T]]

artur-jablonski avatar Jul 28 '22 14:07 artur-jablonski