score:3

Accepted answer

A NodeSeq is not a List, so trying to pattern match it as one will fail. If you wanted to match it using unapplySeq of some kind, you would need to do it in this way:

def exactlyOne[A](xs: Seq[A]): Option[A] = xs match {
  case Seq(head) => Some(head)
  case _ => None
}

scala> exactlyOne(<root>hello</root>)
res5: Option[scala.xml.Node] = Some(<root>hello</root>)

scala> exactlyOne(<root>hello</root><foo>world</foo>)
res6: Option[scala.xml.Node] = None

Related Query

More Query from same tag