如何根据选项添加或不添加 XML 属性?
我写了一个 makeMsg 函数,但我不喜欢它 - 根据 Option.isDefined 进行区分似乎真的不符合 Scala 风格。你能做得更好吗?
scala> def makeMsg(t: Option[String]) =
| if (t.isDefined) <msg text={t.get} /> else <msg />
makeMsg: (t: Option[String])scala.xml.Elem
scala> makeMsg(Some("hello"))
res0: scala.xml.Elem = <msg text="hello"></msg>
scala> makeMsg(None)
res1: scala.xml.Elem = <msg></msg>
I have written a makeMsg function but I don't like it - it just seems really un-Scala-ish to discriminate based on Option.isDefined. Can you make it better?
scala> def makeMsg(t: Option[String]) =
| if (t.isDefined) <msg text={t.get} /> else <msg />
makeMsg: (t: Option[String])scala.xml.Elem
scala> makeMsg(Some("hello"))
res0: scala.xml.Elem = <msg text="hello"></msg>
scala> makeMsg(None)
res1: scala.xml.Elem = <msg></msg>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试以下操作:
如果属性值为
null
- 它将不会添加到元素中。更新
更好!如果您要添加此隐式转换:
您可以像这样使用
t
:这是 REPL 会话:
这有效,因为
scala.xml.UnprefixedAttribute
具有接受的构造函数Option[Seq[Node]]
作为值。You can try this:
if attribute value is
null
- it will not be added to the element.Update
Even better! If you will add this implicit convertion:
you can just use
t
like this:Here is REPL session:
This works because
scala.xml.UnprefixedAttribute
has constructor that acceptsOption[Seq[Node]]
as value.这有什么问题:
不像Easy Angel,但它是直接的 Scala。
What's wrong with this:
Not as concise as Easy Angel's, but it's straight up Scala.
Canonical Scala 不要求文本字段知道在空时巧妙地消失:
每当您有选项但需要使用不知道选项的内容时,您应该考虑使用此模式。 (在这种情况下,Easy Angel 找到了一个更紧凑的解决方案,它确实了解选项或类似的内容。)
Canonical Scala that does not require the text field to know to cleverly disappear when it's empty:
You should think about using this pattern whenever you have an option but need to use something that doesn't know about options. (In this case, Easy Angel has found a more compact solution where it does know about options or something like them.)