Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created April 22, 2015 05:20
Show Gist options
  • Select an option

  • Save trumanw/0e8c7b8c9de508c01d60 to your computer and use it in GitHub Desktop.

Select an option

Save trumanw/0e8c7b8c9de508c01d60 to your computer and use it in GitHub Desktop.
Serialization demo in scala
import java.io._
@SerialVersionUID(124L)
class Person(var name: String)
extends Serializable {
override def toString = f"My name is $name%s."
}
@SerialVersionUID(123L)
class Pet(var name: String, var species: String, var owner: Person)
extends Serializable {
override def toString = {
val ownerName = owner.name
f"$ownerName%s has a $species%s named $name%s"
}
}
object SerializationDemo extends App {
// init person and pet
val person = new Person("Truman Wu")
val pet = new Pet("Jojo", "dog", person)
// serialize two associated objects into the tmp file
val oos = new ObjectOutputStream(new FileOutputStream("./pets2persons"))
oos.writeObject(person)
oos.writeObject(pet)
oos.close
// deserialize the two objects from the file created above
val ois = new ObjectInputStream(new FileInputStream("./pets2persons"))
val personOutput = ois.readObject()
val petOutput = ois.readObject()
ois.close
println(personOutput)
println(petOutput)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment