Template for a codec for a sum type A
.
Template for a codec for a sum type A
.
Each constructor of A
should get assigned a unique index when
implementing this class. It is used to tag
XML trees, so that the
correct decoding function can be chosen.
In addition to the contract of Codec
, instances of this class must
also preserve the index, that is, any index returned by enc
must
produce a valid decoding function in dec
.
Using this is a two-step process: First, create an object extending from
this abstract and implement enc
and dec
accordingly. Second,
call toCodec
with an arbitrary tag on that object to obtain the
actual codec. This process exists to work around a bug in the Scala
compiler.
Example usage
new Variant[Option[A]] { def enc(env: Environment, a: Option[A]): (Int, env.XMLTree) = a match { case Some(a) => (0, Codec[A].encode(env)(a)) case None => (1, Codec[Unit].encode(env)(())) } def dec(env: Environment, idx: Int): Option[env.XMLTree => XMLResult[Option[A]]] = idx match { case 0 => Some(Codec[A].decode(env)(_).right.map(Some.apply)) case 1 => Some(Codec[Unit].decode(env)(_).right.map(_ => None)) case _ => None } } toCodec "option"
Note the closing call to toCodec
. The return type annotations are
required for Scala 2.10.x.
Footnote
The preferred interface would look roughly like this:
def variant[A](env: Environment)(enc: A => (Int, env.XMLTree), dec: Int => Option[env.XMLTree => Result[A]], tag: String): Codec[A]
It can't be realised because some Scala versions have trouble establishing equivalence between path-dependent types.
Obtain an instance of a codec from the implicit scope.
Obtain an instance of a codec from the implicit scope.
Example usage
Codec[Int].encode(env)(3)
Combinators for codecs.