Last active
December 15, 2015 06:38
-
-
Save mmakowski/5217262 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
R1: