开发者

Attributes in XML literals only accept String?

It seems that you have to explicitly specify attribute values in XML literals as strings:

scala> val foo = 3
foo: Int = 3

scala> <bar id={ foo } />
<console>:10: err开发者_StackOverflowor: 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>

Couldn't the constructor simply accept an Any parameter and call toString on it? Since the following works,

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

there's a slight asymmetry in this API. Is there any particular reason for this?


you could 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜