Do [all] Scala [library] objects work properly with Java's XMLEncoder?

I have Scala objects that work properly with

new ObjectOutputStream(new FileOutputStream(filename)).writeObject(this)

but with

new XMLEncoder(new BufferedOutputStream(new FileOutputStream(filename))).writeObject(this)

an outline of an XML file is created, but the object is not contained. No exception is thrown.

Anything Google turns up with Scala, serialization, and XML shows third party libraries being used insead of what is now built into Java.

XMLEncoder works for javabeans. Classes are not javabeans by default. For instance Scala’s case classes are not.

Apparently, you can make Scala classes Java Beans by annotation

I believe that ObjectOutputStream requires a JavaBean as well. This is why the object being serialized looks like

@SerialVersionUID(1L) class SerialTest extends {
@BeanProperty var testing = 6

def incTesting() = testing += 1

def serializeAsBinary(filename: String) = [elided]
def serializeAsXml(filename: String) = [elided]

After I add “extends” and a default constructor, the Person object will serialize as XML! Now if I could only figure out why my object won’t… I’ve tried just about everything.

It looks like Scala noticed that my object contained only the default values and decided not to record any of its vars. If I simply call incTesting() once so that it doesn’t have only default values, the object is written in XML with its members. I thought I had tested that, but apparently not. Thanks for the example Person that convinced me that it should work.

It looks like one problem is that the object I am really trying to serialize includes a scala.collection.mutable.TreeMap. If I try to serialize a plain old TreeMap with none of my own stuff, e.g.,

val map = new TreeMap[String, Double]()
map.put("me", 5)
new XMLEncoder(new BufferedOutputStream(new FileOutputStream("map.xml"))).writeObject(map)

it results in this output to stderr:

java.lang.InstantiationException: scala.collection.mutable.TreeMap
Continuing …
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(TreeMap);
Continuing …

It appears that not all Scala objects can be XML encoded. That wouldn’t be good!