Type Serialization
This page covers serialization of Scala-specific types.
Setup
All examples assume the following setup:
import org.apache.fory.Fory
import org.apache.fory.serializer.scala.ScalaSerializers
val fory = Fory.builder()
.withScalaOptimizationEnabled(true)
.build()
ScalaSerializers.registerSerializers(fory)
Case Class
case class Person(github: String, age: Int, id: Long)
fory.register(classOf[Person])
val p = Person("https://github.com/chaokunyang", 18, 1)
println(fory.deserialize(fory.serialize(p)))
POJO Class
class Foo(f1: Int, f2: String) {
override def toString: String = s"Foo($f1, $f2)"
}
fory.register(classOf[Foo])
println(fory.deserialize(fory.serialize(new Foo(1, "chaokunyang"))))
Object Singleton
Scala object singletons are serialized and deserialized to the same instance:
object MySingleton {
val value = 42
}
fory.register(MySingleton.getClass)
val o1 = fory.deserialize(fory.serialize(MySingleton))
val o2 = fory.deserialize(fory.serialize(MySingleton))
println(o1 == o2) // true
Collection
Scala collections are fully supported:
val seq = Seq(1, 2)
val list = List("a", "b")
val map = Map("a" -> 1, "b" -> 2)
println(fory.deserialize(fory.serialize(seq)))
println(fory.deserialize(fory.serialize(list)))
println(fory.deserialize(fory.serialize(map)))
Tuple
All Scala tuple types (Tuple1 through Tuple22) are supported:
val tuple2 = (100, 10000L)
println(fory.deserialize(fory.serialize(tuple2)))
val tuple4 = (100, 10000L, 10000L, "str")
println(fory.deserialize(fory.serialize(tuple4)))