zio-json
zio-json copied to clipboard
encoding decoding classes with type parameters (scala 2.x) fail compilation
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 Have you tried if def foo[T: JsonEncoder](arg: A[T])
works for your case?
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]]