What does param: _* mean in Scala?

Chris picture Chris · Oct 29, 2011 · Viewed 31.8k times · Source

Being new to Scala (2.9.1), I have a List[Event] and would like to copy it into a Queue[Event], but the following Syntax yields a Queue[List[Event]] instead:

val eventQueue = Queue(events)

For some reason, the following works:

val eventQueue = Queue(events : _*)

But I would like to understand what it does, and why it works? I already looked at the signature of the Queue.apply function:

def apply[A](elems: A*)

And I understand why the first attempt doesn't work, but what's the meaning of the second one? What is :, and _* in this case, and why doesn't the apply function just take an Iterable[A] ?

Answer

Ben James picture Ben James · Oct 29, 2011

a: A is type ascription; see What is the purpose of type ascriptions in Scala?

: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs.

It is completely valid to create a Queue using Queue.apply that has a single element which is a sequence or iterable, so this is exactly what happens when you give a single Iterable[A].