I noticed that scala.xml.Atom takes a type parameter A, even though all of its subclasses extend Atom[String], and the documentation says “The class Atom provides an XML node for text (PCDATA).”
Are there legitimate use cases for instantiating an Atom with a type parameter other than string?
More concretely, I’m interested in using Scala XML literal to define sort of a nice DSL for defining an in-memory tree-based document structure, where many of the nodes would be existing scala classes. It would be super nice to use <document>{new JButton("Hi")}</document> and access the non-text data in the Atom[JButton] without having to define an XML serialization scheme for every existing class.
Is that a legitimate use case, or am I abusing the current implementation of Scala’s XML library?
if you take a look into the sources the reason is revealled. Atom is generic because it converts the passed object to a String. So you can pass a
JButtonto it but then it will just call its toString method. (line 48 is what matters)I guess it is possible to get the data back out of the atom:
returns
6. So your plan would work. I still think a tree based on abstract classes and case classes would be a better choice because with your method all type safety is gone as you can pass in everything, so that type errors will not be discovered until runtime.