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 {
caseSome(a) => (0, Codec[A].encode(env)(a))
caseNone=> (1, Codec[Unit].encode(env)(()))
}
def dec(env: Environment, idx: Int): Option[env.XMLTree => XMLResult[Option[A]]] = idx match {
case0=>Some(Codec[A].decode(env)(_).right.map(Some.apply))
case1=>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:
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 byenc
must produce a valid decoding function indec
.Using this is a two-step process: First, create an object extending from this abstract and implement
enc
anddec
accordingly. Second, calltoCodec
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
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:
It can't be realised because some Scala versions have trouble establishing equivalence between path-dependent types.