Skip to content

Instantly share code, notes, and snippets.

@Gekkio
Created September 6, 2011 11:03
Show Gist options
  • Save Gekkio/1197273 to your computer and use it in GitHub Desktop.
Save Gekkio/1197273 to your computer and use it in GitHub Desktop.
Kryo serializers for Scala None/Some
import com.esotericsoftware.Kryo
import com.estoericsoftware.serialize.SimpleSerializer
import java.nio.ByteBuffer
object OptionSerializers {
def register(kryo: Kryo) {
kryo.register(classOf[None$], new NoneSerializer)
kryo.register(classOf[Some[_]], new SomeSerializer(kryo))
}
}
class NoneSerializer extends SimpleSerializer[None.type] {
def read(buffer: ByteBuffer) = None
def write(buffer: ByteBuffer, o: None.type) = ()
}
class SomeSerializer(kryo: Kryo) extends SimpleSerializer[Some[_]] {
def read(buffer: ByteBuffer) = Some(kryo.readClassAndObject(buffer))
def write(buffer: ByteBuffer, o: Some[_]) = kryo.writeClassAndObject(buffer, o.get)
}
@bhelm
Copy link

bhelm commented Feb 17, 2016

Nice, Thank you.

@arungupta2008
Copy link

i used this code and it was not working. I made few changes have a look at it.

`import com.esotericsoftware.kryo.io.{Input, Output}
import com.esotericsoftware.kryo.{Kryo, Serializer}

object OptionSerializers {
def register(kryo: Kryo, noneCode: Int, someCode: Int) {
kryo.register(Class.forName("scala.None$"), new NoneSerializer(), noneCode)
kryo.register(classOf[Some[_]], new SomeSerializer(kryo), someCode)
}
}

class NoneSerializer extends Serializer[None.type] {
override def write(kryo: Kryo, output: Output, object: None.type): Unit = ()

override def read(kryo: Kryo, input: Input, type: Class[None.type]): None.type = None
}

class SomeSerializer(kryo: Kryo) extends Serializer[Some[]] {
override def write(kryo: Kryo, output: Output, object: Some[
]): Unit = kryo.writeClassAndObject(output, object.get)

override def read(kryo: Kryo, input: Input, type: Class[Some[]]): Some[] = Some(kryo.readClassAndObject(input))
}`

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