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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With