7

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

Daniel Shin
  • 5,086
  • 2
  • 30
  • 53

1 Answers1

8

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)
Jason Scott Lenderman
  • 1,908
  • 11
  • 14
  • Interesting. So am I correct to think that `_*` is a **special construct** rather than another complex underscore rule, which I failed to understand? I've yet to encounter another example where underscore is used to annotate type (except for _existential type_). Thanks – Daniel Shin Oct 02 '15 at 04:40
  • "sequence argument" http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#function-applications – som-snytt Oct 02 '15 at 04:44
  • Corresponds to "sequence wildcard" in "pattern sequence", http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-sequences – som-snytt Oct 02 '15 at 04:46
  • 1
    Another _hidden_ feature in Scala. Thank you! – Daniel Shin Oct 02 '15 at 04:57