Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala underscore asterisk in Variadic Function? [duplicate]

Tags:

scala

I'm currently following Functional Programming In Scala

This is the psuedo-implementation of apply in List[A]

def apply[A](as: A*): List[A] = 
  if (as.isEmpty) Nil
  else ::(as.head, apply(as.tail: _*))

If I omit : _* in as.tail: _*, scala complains for type mismatch, which makes sense since as.tail is Seq[A] here.

But what does _* exactly do here?

Edit::

Correct terminology for such is sequence wildcard

like image 571
Daniel Shin Avatar asked Oct 02 '15 04:10

Daniel Shin


1 Answers

The : _* notation just tells the scala compiler to treat the elements of the collection that you passed into the method (the collection which proceeds : _* in the arguments) as if they had been passed one by one into the varargs method. For example, if you have

def foo(x: Int*) = x.sum
val xs = Seq(1, 2, 3, 4)

then

foo(xs: _*)

works as if you had typed

foo(1, 2, 3, 4)
like image 160
Jason Lenderman Avatar answered Sep 28 '22 17:09

Jason Lenderman