Search code examples
scalascala-xml

How to convert a Sequence of scala.xml.Attribute to scala.xml.MetaData?


There's not much to add here. Of course I'm able to get it done somehow with an imperative coding style, but I'm curious how this can be solved nicely.

def this( arguments: Seq[(String, String)], merges: Seq[(String, String)]) = this
{
    val metadata: Seq[Attribute] = ( arguments ++ merges ).groupBy( _._1 ).map
    {
        case (key, value) => Attribute( None, key, Text( value.map( _._2 ).mkString( " " ) ), Null )
    }

    var result: MetaData = Null

    for( m <- metadata ) result = result.append( m )

    result
}

Solution

  • How about this?

    metadata.fold(Null)((soFar, attr) => soFar append attr)
    

    So you can do away with intermediate variable altogether if you are so inclined. In full:

    def foo(arguments: Seq[(String, String)], merges: Seq[(String, String)]) =
      (arguments ++ merges).groupBy(_._1).map {
        case (key, value) => Attribute(None, key, Text(value.map(_._2).mkString(" ")), Null)
      }.fold(Null)((soFar, attr) => soFar append attr)