Search code examples
scalascala-2.8lift

How do I convert Array[Node] to NodeSeq?


I'm trying to integrate a Lift application into some existing Java code. In one of my snippets, I have an Array of Java objects that I need to map that into a NodeSeq. I can get an Array of Node's, but not a NodeSeq. (At least, not in very functional-looking way).

import scala.xml.NodeSeq

// pretend this is code I can't do anything about
val data = Array("one", "two", "three")

// this is the function I need to write
def foo: NodeSeq = data.map { s => <x>{s}</x> }
//                          ^
// error: type mismatch;
//  found   : Array[scala.xml.Elem]
//  required: scala.xml.NodeSeq

What's the cleanest way to do this?


Solution

  • I would simply convert map output to sequence (given that Seq[Node] is a super-class of NodeSeq)

    scala> def foo: NodeSeq = data.map { s => <x>{s}</x> } toSeq
    foo: scala.xml.NodeSeq
    

    or use foldLeft instead of map

    scala> def foo: NodeSeq = (Seq[Node]() /: data) {(seq, node)=> seq ++ <x>{node}</x>}
    foo: scala.xml.NodeSeq