Quantcast

[scala] Embedded expression types in XML literals

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

[scala] Embedded expression types in XML literals

Kristian Domagala
I find the behaviour of embedded Scala expressions in XML literals to be a bit inconsistent, and contradictory to the type safety of the rest of the language. Consider the following:


Welcome to Scala version 2.7.2.RC6 (Java HotSpot(TM) Client VM, Java 1.5.0_13).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.xml.Text
import scala.xml.Text

scala> implicit def IntText(i:Int):Text = Text("My int '" + i + "' as text")
IntText: (Int)scala.xml.Text

scala> <elt attr={4} />
res0: scala.xml.Elem = <elt attr="My int '4' as text"></elt>

scala> <elt>{4}</elt>
res1: scala.xml.Elem = <elt>4</elt>


When used in an attribute, the value of the expression is converted to a Text instance using the implicit def (presumably because of the UnprefixedAttribute constructor). However, in the context of an embedded node, the expression value is toString'ed (presumably because the value is not an instance of Node). I understand enough of the logic behind this to realise that I can get the desired result by using <elt>{4:Text}</elt>, but it's one more thing I have to remember when working with XML literals in Scala.

I'm sure there is a good reason for making the trade-off of type safety by accepting Any type as the result of an embedded expression, but I find it odd that there doesn't appear to be any attempt made to use an implicit conversion before resorting to using toString. Is there something I am missing in this regard? Are there any archived discussions about these decisions that I can browse? I haven't had much luck so far with the search terms I've used.

I find the XML literal support in Scala to be a great feature, however, I'm disappointed whenever I run into unexpected behaviour at run-time that I thought I had covered at compile time. Regardless of whether or not the implicit conversion could be used under the above circumstances, I think it would be very useful to have a compiler flag to warn when the value of an expression in an XML literal is not a Node and will be converted to a Text node using toString. I haven't seen anything to indicate that this is available, so I'm thinking about the possibility of writing a compiler plugin for this feature. Does anyone have any opinion on the feasibility of such a task?

All comments/suggestions/enlightenment appreciated.

Cheers,
Kristian.

Loading...