Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does param: _* mean in Scala?

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] ?

like image 215
Chris Avatar asked Oct 29 '11 11:10

Chris


People also ask

What is a parameter in Scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

What does => mean in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is type ascription in Scala?

Type ascription is just telling the compiler what type you expect out of an expression, from all possible valid types.

What is Scala syntax?

The biggest syntactic difference between Scala and Java is that the ';' line end character is optional. When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other's methods.


2 Answers

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].

like image 168
Ben James Avatar answered Sep 20 '22 03:09

Ben James


This is a special notation that tells the compiler to pass each element as its own argument, rather than all of it as a single argument. See here.

It is a type annotation that indicates a sequence argument and is mentioned as an "exception" to the general rule in section 4.6.2 of the language spec, "Repeated Parameters".

It is useful when a function takes a variable number of arguments, e.g. a function such as def sum(args: Int*), which can be invoked as sum(1), sum(1,2) etc. If you have a list such as xs = List(1,2,3), you can't pass xs itself, because it is a List rather than an Int, but you can pass its elements using sum(xs: _*).

like image 23
Luigi Plinge Avatar answered Sep 21 '22 03:09

Luigi Plinge