patkua@work

String XML interpolation in Scala

In java, if you’re formatting a small XML document, it might be tempting to simply do a String.format to substitute it directly into a string. Transitioning into scala, this is then easy to convert into one of their XML representations with XML.loadString. You might very well end up with code that looks like this:

val myValue = "will be substituted"
val xml = XML.loadString(String.format("<node>%s</node>", node))

You can actually just do this inline with scala directly, and end up with this instead

val myValue = "will be substituted"
val xml = <node>{myValue}</node>

Neat-o!

Exit mobile version