如何根据选项添加或不添加XML属性?
我已经写了一个makeMsg函数,但我不喜欢它——它看起来真的不适合根据Option.isDefined进行区分。你能做得更好吗如何根据选项添加或不添加XML属性?,xml,scala,Xml,Scala,我已经写了一个makeMsg函数,但我不喜欢它——它看起来真的不适合根据Option.isDefined进行区分。你能做得更好吗 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("hel
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>
scala>def makeMsg(t:Option[String])=
|如果(t.isDefined)else
makeMsg:(t:Option[String])scala.xml.Elem
scala>makeMsg(一些(“你好”))
res0:scala.xml.Elem=
scala>makeMsg(无)
res1:scala.xml.Elem=
您可以尝试以下方法:
def makeMsg(t: Option[String]) = <msg text={t orNull} />
您可以这样使用t
:
def makeMsg(t: Option[String]) = <msg text={t} />
def makeMsg(t:Option[String])=
以下是REPL会话:
scala> import xml.Text
import xml.Text
scala> implicit def optStrToOptText(opt: Option[String]) = opt map Text
optStrToOptText: (opt: Option[String])Option[scala.xml.Text]
scala> def makeMsg(t: Option[String]) = <msg text={t} />
makeMsg: (t: Option[String])scala.xml.Elem
scala> makeMsg(Some("hello"))
res1: scala.xml.Elem = <msg text="hello"></msg>
scala> makeMsg(None)
res2: scala.xml.Elem = <msg ></msg>
scala>导入xml.Text
导入xml.Text
scala>隐式def optstrttooptext(opt:Option[String])=opt-map-Text
optstrttooptext:(opt:Option[String])Option[scala.xml.Text]
scala>defmakemsg(t:Option[String])=
makeMsg:(t:Option[String])scala.xml.Elem
scala>makeMsg(一些(“你好”))
res1:scala.xml.Elem=
scala>makeMsg(无)
res2:scala.xml.Elem=
这是因为
scala.xml.unfixedAttribute
具有接受选项[Seq[Node]]
作为值的构造函数。这有什么问题:
def makeMsg(t: Option[String]) = t match {
case Some(m) => <msg text={m} />
case None => <msg />
}
def makeMsg(t:Option[String])=t匹配{
案例部分(m)=>
案例无=>
}
不像的那样简洁,但它是直接的Scala。规范Scala不需要知道文本字段在为空时会巧妙地消失:
t.map(s => <msg text={s} />).getOrElse(<msg />)
t.map(s=>).getOrElse()
当您有一个选项但需要使用一些不了解选项的东西时,您应该考虑使用此模式。(在这种情况下,Easy Angel找到了一个更紧凑的解决方案,它确实知道选项或类似的东西。)直接这么做肯定足够简单,隐式只是添加了样板<代码>def makeMsg(t:Option[String])=。它也让人感觉更安全,你被意料之外的暗示刺痛的风险更小。我认为这取决于上下文。当然,在本例中更容易直接使用它
text={t map text}
。但是,例如,如果我编写了一些生成大量XML的应用程序,那么创建object xmlclimits
是有意义的,我将到处导入并将这种样板文件移到那里。我认为如果您有几个选项属性,那么使用这种方法可能会有问题。但是对于这个简单的例子,它也可以。
t.map(s => <msg text={s} />).getOrElse(<msg />)