I have a list of strings and I need to join them together with <br/> tags in between. So starting from:
val list = List("line1", "line2", "line3")
I need to end up with a NodeSeq of:
line1<br/>line2<br/>line3
It's possible the list contains only one element, in which case I should end up with a NodeSeq just of Text("line1").
Is there a one-liner to do this, using one of the higher order functions on list? I've tried to play around with foldLeft but can't seem to get it to do what I want.
list.map(scala.xml.Text(_):scala.xml.NodeSeq).reduce(_ ++ <br /> ++ _)
Note that we have to widen the type to scala.xml.NodeSeq
manually as Text
is too restrictive for the reduce
method. The more concise
list.map(scala.xml.Text).reduce(_ ++ <br /> ++ _)
won’t compile.
If you don't mind using Scalaz, there's intersperse
:
import scalaz._
import Scalaz._
list.map(xml.Text(_): xml.Node).intersperse(<br/>): xml.NodeSeq
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