Skip to content

Instantly share code, notes, and snippets.

@themoritz
Created January 28, 2021 00:05
Show Gist options
  • Save themoritz/87af7c71b3467d8186eed67528a2c55b to your computer and use it in GitHub Desktop.
Save themoritz/87af7c71b3467d8186eed67528a2c55b to your computer and use it in GitHub Desktop.
Custom Serialization in Kotlin
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
data class Moritz(val x: Int)
data class Foo(
@Transient
var bar: Moritz,
val baz: Int
) : Serializable {
private fun writeObject(oss: ObjectOutputStream) {
oss.defaultWriteObject()
oss.writeObject(10)
}
private fun readObject(ois: ObjectInputStream) {
ois.defaultReadObject()
bar = Moritz(ois.readObject() as Int)
}
}
val foo = Foo(Moritz(1), 1)
val os = ByteArrayOutputStream()
val oos = ObjectOutputStream(os).writeObject(foo)
val bs = os.toByteArray()
val recovered = ObjectInputStream(bs.inputStream()).readObject() as Foo
println(recovered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment