XML 文本中的属性只接受字符串?
看来您必须将 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 存在轻微的不对称性。这有什么特别的原因吗?
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: 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>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为这种情况添加隐式转换:
you could add an implicit conversion for this case: