Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does scala.Serializable not specify any methods?

Because the Java language required all interface members to be public and the original designers didn't want to force the "methods" of java.io.Serializable to be public, this was not possible in Java.

Scala doesn't have this restriction, but things like readObject/writeObject are still not specified in the scala.Serializable trait.

Wouldn't this help developers because

  • they had a guarantee that their signature is correct
  • it would make accessing these methods less akward.

or do I miss something important?

like image 380
soc Avatar asked Jun 11 '11 21:06

soc


People also ask

What are the methods in Serializable interface?

Serializable doesn't contain any method, it's the ObjectOutputStream and ObjectInputStream classes that can do that work, through the writeObject and readObject methods. Serializable is just a marker interface, in other words it just puts a flag, without requiring any fields or methods.

What is Serializable in Scala?

Serializing an object means taking the data stored in an object and converting it to bytes (or a string). Suppose you want to write the data in an object to a JSON file. JSON files store strings. JSON has no understanding about the JVM or Scala objects.

What is a Serializable interface?

The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods. Classes implement it if they want their instances to be Serialized or Deserialized.

Is string serializable in Scala?

String does not implement scala. Serializable. There are no dependencies from Java to Scala.


1 Answers

or do I miss something important?

Yes, you do.

readObject/writeObject methods have to be private and NOT overridden for the mechanism to work properly.

They are called in reverse way (i.e. superclass->class) too. Morealso you do wish that the method remains private to prevent misuse (and explicit calls)

Serializable mechanism offers other methods as well: like writeReplace+readResolve, that are usually not used in the same class + readObjectNoData (that's not so useful).

Now if you need specific method take a look at java.io.Externalizable. It does publish its methods and implementing it overrides the default serialization mechanism.

like image 58
bestsss Avatar answered Oct 09 '22 19:10

bestsss