5

I'm building an XML by pieces using different functions such as the following example:

<xml>
  { maybeXml(param) }
</xml>

And trying to return an Empty or Non-empty NodeSeq based on the value of the param such as:

def maybeXml(param: Boolean): NodeSeq = {
  if(param) <someXml></someXml>
  else ??? //Empty or None doesn't work
}

The solution I'm using now is just defining the function type as Option[NodeSeq] and then using it as maybeXml.getOrElse(""), but that doesn't make that much sense to me. My current usage is as follows:

<xml>
  { maybeXml(param).getOrElse("") }
</xml>

def maybeXml(param: Boolean): NodeSeq = {
  if(param) Some(<someXml></someXml>)
  else None
}

Is a better way to express this using an Empty NodeSeq directly?

chaotive
  • 182
  • 14

1 Answers1

8

For empty NodeSeq use NodeSeq.Empty

def maybeXml(param: Boolean): NodeSeq = {
  if(param) <someXml></someXml>
  else NodeSeq.Empty
} 
Łukasz
  • 8,555
  • 2
  • 28
  • 51
  • Thanks, this does work for a function of type NodeSeq. But, I also have the case of a function returning just a single Node. Any ideas of how can I handle that case? – chaotive Apr 27 '16 at 16:46
  • Well, maybe there is a better solution, but `Elem` is `Node` and `Node` is `NodeSeq` so you can create a function that returns `NodeSeq` like this `def get(p: Boolean): NodeSeq = if (p) 123 else NodeSeq.Empty` – Łukasz Apr 27 '16 at 17:07
  • No, the problem with that is it forces me to change the type of something that strictly returns 0 or 1 node (Node type), to a possible sequence of 0 to many nodes (NodeSeq type). My functions needs to describe what is the possible result correctly. I have created [another question](http://stackoverflow.com/questions/36896156/how-to-return-empty-node-using-scala-xml) for that topic thought. – chaotive Apr 27 '16 at 17:53