您似乎必须将XML文字中的属性值显式指定为字符串:
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>
构造函数不能简单地接受Any参数并在其上调用toString吗?由于以下工作,
scala> <bar>{ foo }</bar>
res21: scala.xml.Elem = <bar>3</bar>
此API存在轻微的不对称性。这有什么特别的原因吗?
答案 0 :(得分:3)
你可以为这种情况添加隐式转换:
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>