Another Tour of Scala


The Gist

XML Processing describes Scala’s native support for XML.

My Interpretation

Scala supports XML literals. Meaning that this program:

outputs this:

This syntax can do more than just save you a few quotes and backslashes, however. You can use curly braces to dynamically insert expressions, as such:

Note how we don’t quote the title or href attributes; Scala knows that we are assigning XML attributes to dynamic variables (i.e. this isn’t just blind templating; it’s XML-aware). Also note how the quoted string we pass to the function gets escaped inside the attribute value.

Making it more dynamic

Inside those curly braces, we can embed any Scala expression we want, so if we wanted to take a list and output it as a ul, this would work just fine:

Notice that inside our expression, we map our list of strings to a list of XML literals, themselves containing a dynamic expression.

Also note that we can put literal curly braces in by either doubling them outside of an attribute, or quoting them as an attribute’s value.

My Thoughts on this Feature

I think XML is one of the most abused and over-used pieces of software technology ever invented. So, on the one hand, any feature that makes using XML easier is immediately questionable. On the other hand, however, XML is a fact of life, and the way Scala supports XML literals is pretty nice, and very intuitive. I do find it curious why regular expression literals are not supported, as they are far more useful than XML.