Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a Scala class that extends a Java class: value lost?

Foo.java

public class Foo{
  public int i = 0;
}

Bar.scala

class Bar() extends Foo with Serializable{
  i = 1 
}

Serialization via Josh Seureth https://stackoverflow.com/a/3442574/390708

import java.io._

  class Serialization{
    def write(x : AnyRef) {
    val output = new ObjectOutputStream(new FileOutputStream("test.obj"))
    output.writeObject(x)
    output.close()
  }

  def read[A] = {
    val input = new ObjectInputStream(new FileInputStream("test.obj"))
    val obj = input.readObject()
    input.close()
    obj.asInstanceOf[A]
  }
}

REPL session, bar is 1 before serialization but 0 after.

scala -cp .
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_03).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val bar = new Bar
bar: Bar = Bar@2d2ab673

scala> bar.i
res0: Int = 1

scala> :load Serialization.scala
Loading Serialization.scala...
import java.io._
defined class Serialization

scala> val serialization = new Serialization
serial: Serialization = Serialization@41a45f89

scala> serialization.write(bar)

scala> val bars = serialization.read[Bar]
bars: Bar = Bar@5a9948fd

scala> bars.i
res3: Int = 0

So, why isn't bars.i 1 in this case?

like image 625
Brian Avatar asked Feb 20 '23 20:02

Brian


1 Answers

This is expected and I believe has nothing to do with Scala. Non-Serializable superclasses are not serialized out (as they are not serializable!) and thus their values will be initialized by the default constructor.

If you want to somehow save the superclass, you'll need to override your readObject and writeObject to save the state manually. Or, use a more flexible serialization solution that writes XML, JSON, etc. and uses reflection.

like image 194
Steven Schlansker Avatar answered Feb 23 '23 09:02

Steven Schlansker