Saturday, December 31, 2011

Converting from a List or Seq or similar to varargs

Ever run across a situation in Java (okay - probably not), where you need to convert a List of things into a varargs group?  I have in Scala today, and I found the solution on stackoverflow, but I figured I'd repost it here.

The use case I have is the HTML fixer-upper that I'm writing.  I need to covert a list of elements that are returned by my conquer function into a varargs group that is passed to the Elem() constructor:

val childrenList : List[Node] = conquer(remainText)
Elem(null, name, attrs, TopScope, childrenList : _*)

I don't truly understand the Scala magic that is at work here.  If I recall, any operator ending in : is right associative, but I think a single : is a slightly different case that's a built-in, but even so, it seems a bit magical.  Should probably look it up.

1 comment:

  1. Thanks for this! I needed this today, and I must say it is a bit odd. I was expecting something like [A]* or something along those lines, which is used for specifying the type in a definition (i.e. Person*).

    ReplyDelete