简体   繁体   中英

Option[Elem] in Scala XML

val i = Some(<foo/>)
<bar>{for(o <- i) yield o}</bar>

returns the strange value:

res3: scala.xml.Elem = <bar>Some(&lt;foo/&gt;)</bar>

Obviously not the intended result. I can get around by writing:

<bar>{for(o <- i.toList) yield o}</bar>

which returns the intended result:

<bar><foor></foo></bar>

but why do I need to do this conversion? Is there any trait that I should cast i to, instead of converting it to a List ?

Because Option.map (which is what your for-comprehension uses) returns another Option , and there is no implicit conversion from Option to Seq or similar (the reasons for which are debatable and have been debated). While Option has a number of collection-like methods on it, it doesn't actually implement any of the main collection traits so the XML system doesn't know to treat it as a collection of elements.

However, barnesjd is correct that your for-comprehension is not needed, you should be able to just convert the Option to a List or Seq and leave it at that.

scala> <bar>{i.toSeq}</bar>
res2: scala.xml.Elem = <bar><foo/></bar>

The expression for(o <- i) yield o is sort of a no-op... Perhaps this is what you intended?

scala> for{ o <- i } yield { <bar>{o}</bar> }
res3: Option[scala.xml.Elem] = Some(<bar><foo/></bar>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM