Attributes in XML literals accept only String?

It seems that you should explicitly specify attribute values ​​in XML literals as strings:

scala> val foo = 3
foo: Int = 3

scala> <bar id={ foo } />
<console>:10: error: overloaded method constructor UnprefixedAttribute with alternatives:
  (key: String,value: Option[Seq[scala.xml.Node]],next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: String,next: scala.xml.MetaData)scala.xml.UnprefixedAttribute <and>
  (key: String,value: Seq[scala.xml.Node],next1: scala.xml.MetaData)scala.xml.UnprefixedAttribute
 cannot be applied to (java.lang.String, Any, scala.xml.MetaData)
<bar id={ foo } />
 ^

scala> <bar id={ foo.toString } />
res16: scala.xml.Elem = <bar id="3"></bar>

Could the constructor just accept the Any parameter and call onString? Since the following work,

scala> <bar>{ foo }</bar>
res21: scala.xml.Elem = <bar>3</bar>

There is a slight asymmetry in this API. Is there any special reason for this?

+5
source share
1 answer

you can add an implicit conversion for this case:

scala> val foo = 3
foo: Int = 3

scala> implicit def anyToText( a: AnyVal ) = xml.Text( a.toString )
anyToText: (a: AnyVal)scala.xml.Text

scala> <bar id={foo}/>                                         
res2: scala.xml.Elem = <bar id="3"></bar>
+3
source

All Articles