我很容易一般导出的编解码器为一个密封的箱体类家庭这样的:推导瑟茜编解码器为一个密封的箱体类家族,其中碱性状具有(密封)型构件
import io.circe._
import io.circe.generic.auto._
sealed trait Base
case class X(x: Int) extends Base
case class Y(y: Int) extends Base
object Test extends App {
val encoded = Encoder[Base].apply(Y(1))
val decoded = Decoder[Base].apply(encoded.hcursor)
println(decoded) // Right(Y(1))
}
然而,如果我添加类型成员的基类,我不能这样做了,即使它是由一个密封的特质界:
import io.circe._
import io.circe.generic.auto._
sealed trait Inner
case class I1(i: Int) extends Inner
case class I2(s: String) extends Inner
sealed trait Base { type T <: Inner }
case class X[S <: Inner](x: S) extends Base { final type T = S }
case class Y[S <: Inner](y: S) extends Base { final type T = S }
object Test extends App {
val encodedInner = Encoder[Inner].apply(I1(1))
val decodedInner = Decoder[Inner].apply(encodedInner.hcursor) // Ok
println(decodedInner) // Right(I1(1))
// Doesn't work: could not find implicit for Encoder[Base] etc
// val encoded = Encoder[Base].apply(Y(I1(1)))
// val decoded = Decoder[Base].apply(encoded.hcursor)
// println(decoded)
}
有没有一种方法,我可以实现我想要什么?如果不是,我可以改变什么来获得类似的东西?
如果您尝试使用辅助模式,该怎么办?例如'Aux [A <:Input] = Base {type T = A}'然后从'Aux'扩展?另外,你是否真的需要它是一个类型成员? – pyrospade
事实上,似乎你的案例类可能只是将'Inner'作为它们的参数,而不是'S <:Inner'。 – pyrospade
我添加了一个答案,但后来修改它以添加更多的细节和解释,以及更好的实现。 – pyrospade