Why is scala.xml.Atom parameterized?

I noticed that it scala.xml.Atomaccepts a type parameter A, although all its subclasses extend Atom[String], and the documentation says: "The Atom class provides an XML node for text (PCDATA)."

Are there any legitimate use cases for an Atom instance with a type parameter other than a string?

More specifically, I am interested in using the Scala XML literal to define a kind of DSL to define the structure of a tree-based document in which many of the nodes will exist in the Scala class. It would be nice to use <document>{new JButton("Hi")}</document>and access non-textual data Atom[JButton]without having to define an XML serialization scheme for each existing class.

Is this a legitimate use case, or am I abusing the current implementation of the Scala XML library?

+3
source share
2 answers

if you look at the sources , the reason is revealed. Atom is generic because it converts the passed object to String. That way you can pass it to it JButton, but then it just calls the toString method. (line 48 matters)

I think you can return data from an atom:

val doc = <document>{ 42 }</document>

doc.child.head match { 
  case i: Atom[Int] => i.data / 7 
  case _ => error("Unsupported type")
}

returns 6. So your plan will work. I still think that a tree based on abstract classes and class classes would be the best choice, because with your method all types of security will disappear, because you can go through everything so that type errors are not detected before execution.

+3

http://sites.google.com/site/burakemir/scalaxbook.docbk.html?attredirects=0, , Atom , , int, ".

, , ,

<foo>{42}</foo>

Atom [Int].

,

<foo life={new Atom(42)}>

( "" Atom (42), - Atom case, .)

, , , , .

, . XML Scala , .

+3

Source: https://habr.com/ru/post/1795280/


All Articles