-2

In scala, I think a field of a object will be static and not be serialized when serializing, but if the field is non serializable, a NotSerializableException got. Why ? Similar java code is OK.

Below is a simple example.

Thanks

Scala code:

package test

import java.io._
import java.util

object AStudent extends Serializable {
  var name="Jack"
  val map=new util.WeakHashMap

}

object SerializationDemo extends App {

  val oos = new ObjectOutputStream(new FileOutputStream("./tmp/stu"))
  println(AStudent.name)
  AStudent.name=null
  println(AStudent.name)
  oos.writeObject(AStudent)
  oos.close

}

Java code:

package test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.WeakHashMap;

public class Stu implements Serializable {
    public static String name="Jack";
    public static WeakHashMap map=new WeakHashMap();
    public static void main(String[] args) throws IOException {
        ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream("./tmp/stu"));
        oos.writeObject(new Stu());
        oos.close();
    }
}
Lee John
  • 1
  • 1
  • In general when asking about exceptions you might want to add the stacktrace. Besides that note that the Scala code and the Java code should not be equivalent (although I don't know Scala very much) as one has instance fields while the other has class fields (aka static). – Thomas Oct 24 '18 at 10:24
  • Scala has no concept of `static` fields. You can "think" of members of an object `A` as being similar to `static` in Java. Keywords being "think similar" and not actually being static. The object `AStudent` will be an instance of an anonymous class `AStudent.type` and all the members of object `AStudent` are actually members of class `AStudent.type`. – sarveshseri Oct 24 '18 at 10:31

2 Answers2

0

The examples are not equivalent. In Java example you are serializing a Stu instance, the serialization will skip static fields as they are not part of the instance state. In Scala example you are serializing a AStudent object instance which has a map field. Since Scala don't have static concept, the Java equivalent would be:

public class AStudent implements Serializable {
  public Map map = new WeakHashMap();    
Karol Dowbecki
  • 38,744
  • 9
  • 58
  • 89
0

Scala has no concept of static fields. You can "think" of members of an object A as being similar to static in Java.

Keywords being "think similar to static" and not actually being static.

The object AStudent will be an instance of an anonymous class AStudent.type and all the members of object AStudent are actually members of class AStudent.type

It is similar to,

class AStudentType[K, V](
    var name: String ="Jack",
    val map: WeakHashMap[K, V] = new WeakHashMap()
)

val AStudent = new AStudentType[String, String]()
sarveshseri
  • 10,459
  • 25
  • 43