Skip to content

Instantly share code, notes, and snippets.

@mmakowski
Last active December 15, 2015 06:38
Show Gist options
  • Save mmakowski/5217262 to your computer and use it in GitHub Desktop.
Save mmakowski/5217262 to your computer and use it in GitHub Desktop.
case class Env()
case class A(env: Env, b: B)
case class B()
trait Serialisation[T, U, -C] {
def serialised(obj: T): U
def deserialised(obj: U, context: C): T
}
trait ContextFreeSerialisation[T, U] extends Serialisation[T, U, Any] {
def deserialised(obj: U, context: Any) = deserialised(obj)
def deserialised(obj: U): T
}
object raise {
def badFormat(str: String) = throw new IllegalArgumentException("bad format: " + str)
}
class ASerialisation(bSer: Serialisation[B, String, Env]) extends Serialisation[A, String, Env] {
val Pattern = """\{b: (.+)\}""".r
def serialised(a: A) = "{b: %s}".format(bSer.serialised(a.b))
def deserialised(str: String, env: Env) = str match {
case Pattern(bStr) => A(env, bSer.deserialised(bStr, env))
case _ => raise badFormat str
}
}
class BSerialisation extends ContextFreeSerialisation[B, String] {
def serialised(b: B) = "{}"
def deserialised(str: String) = str match {
case "{}" => B()
case _ => raise badFormat str
}
}
@mmakowski
Copy link
Author

R1:

scala> val as = new ASerialisation(new BSerialisation)
<console>:20: error: type mismatch;
 found   : BSerialisation
 required: Serialisation[B,String,Env]
Note: Any >: Env (and BSerialisation <: Serialisation[B,String,Any]), but trait Serialisation is invariant in type C.
You may wish to define C as -C instead. (SLS 4.5)
       val as = new ASerialisation(new BSerialisation)
                                   ^

@mmakowski
Copy link
Author

R2:

scala> val as = new ASerialisation(new BSerialisation)
as: ASerialisation = ASerialisation@3ff9ddb5

scala> as.serialised(A(Env(), B()))
res2: String = {b: {}}

scala> as.deserialised("{b: {}}", Env())
res3: A = A(Env(),B())

so far, so good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment