Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a scala.xml.NodeSeq to a Elem?

Tags:

scala

I'm trying to reduce a list of elements

List(1, 2, 3).map{n => <a>{n}</a>}.reduce{(a,b)=> a ++ b}

But I get this error

<console>:8: error: type mismatch;
 found   : scala.xml.NodeSeq
 required: scala.xml.Elem
       List(1, 2, 3).map{n => <a>{n}</a>}.reduce{(a,b)=> a ++ b}

How do I cast a NodeSeq to a Elem?

like image 226
k107 Avatar asked Sep 30 '22 13:09

k107


2 Answers

I wouldn't use reduce in this case. Instead, try foldLeft:

List(1, 2, 3).map{n => <a>{n}</a>}.foldLeft(NodeSeq.Empty){(a,b)=> a ++ b}

I have a whole blog post on map, reduce, and fold that may help if you're new to functional programming.

like image 189
joescii Avatar answered Oct 03 '22 01:10

joescii


In addition to joescii's answer, you don't even need to use foldLeft to generate a sequence of nodes. Since List is already a sequence and Seq[Node] which is implicitly converted to NodeSeq you can just write the following:

val x : NodeSeq = List(1, 2, 3).map{n => <a>{n}</a>}

In addition, since the sequence of nodes is not a valid XML document (breaks single root element contract), you'd probably use this as a interim step in generating XML and subsequently wrap those nodes with some parent element.

If that's the case, than the explicit conversion to NodeSeq is unnecessary as it will be done implicitly as the example below demonstrates:

val x = List(1, 2, 3).map{n => <a>{n}</a>}
<b>{x}</b>
like image 41
Norbert Radyk Avatar answered Oct 03 '22 03:10

Norbert Radyk