Skip to content

Instantly share code, notes, and snippets.

@bsidhom
Last active October 18, 2015 18:32
Show Gist options
  • Save bsidhom/9798005 to your computer and use it in GitHub Desktop.
Save bsidhom/9798005 to your computer and use it in GitHub Desktop.
Example serialization of a Shapeless record type with Chill/Kryo.
import shapeless._
import shapeless.record._
import shapeless.ops.record.{Keys, Values}
import shapeless.syntax.singleton._
import com.esotericsoftware.kryo.io.{Input, Output}
import com.twitter.chill.ScalaKryoInstantiator
import java.io.ByteArrayOutputStream
object ShapelessKryo {
def main(args: Array[String]) {
val author = Witness("author")
val title = Witness("title")
val id = Witness("id")
val price = Witness("price")
type Book = String with KeyTag[author.T, String] ::
String with KeyTag[title.T, String] ::
Long with KeyTag[id.T, Long] ::
Double with KeyTag[price.T, Double] ::
HNil
val book: Book =
("author" ->> "Benjamin Pierce") ::
("title" ->> "Types and Programming Languages") ::
("id" ->> 262162091L) ::
("price" ->> 44.11) ::
HNil
val instantiator = (new ScalaKryoInstantiator).setRegistrationRequired(true)
val kryo = instantiator.newKryo
kryo.register(HNil.getClass)
kryo.register(classOf[Book])
val output = new Output(new ByteArrayOutputStream)
kryo.writeObject(output, book)
val bytes = output.toBytes
println(s"serialized value: ${bytes.mkString("Array(", ", ", ")")}")
val deserialized = kryo.readObject(new Input(bytes), classOf[Book])
println(s"deserialized value: $deserialized")
println(s"author: ${deserialized("author")}")
println(s"price: ${deserialized("price")}")
}
}
@bsidhom
Copy link
Author

bsidhom commented Mar 27, 2014

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