How do I add an XML attribute, or not, depending on an Option?

后端 未结 3 1152
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 08:28

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?



        
3条回答
  •  太阳男子
    2020-12-31 08:44

    You can try this:

    def makeMsg(t: Option[String]) = 
    

    if attribute value is null - it will not be added to the element.

    Update

    Even better! If you will add this implicit convertion:

    import xml.Text
    implicit def optStrToOptText(opt: Option[String]) = opt map Text
    

    you can just use t like this:

    def makeMsg(t: Option[String]) = 
    

    Here is REPL session:

    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]) = 
    makeMsg: (t: Option[String])scala.xml.Elem
    
    scala> makeMsg(Some("hello"))
    res1: scala.xml.Elem = 
    
    scala> makeMsg(None)
    res2: scala.xml.Elem = 
    

    This works because scala.xml.UnprefixedAttribute has constructor that accepts Option[Seq[Node]] as value.

提交回复
热议问题