2

Possible Duplicate:
Syntax sugar: _*

I wrote a function that gets passed a format string (for String.format(...)) and a varargs array of parameters (among other things). The method looks like this:

def myMethod(foo: Number, formatStr: String, params: Any*): Unit = {
  // .. some stuff with foo
  println(formatStr, params.map(_.asInstanceOf[AnyRef]) : _*)
}

I got the syntax for the params argument here. It works! But how? I do not understand the syntax of the second argument to println, particularly the ending part (: _*). It is obviously calling map and expanding the array to a sequence of AnyRefs.

Community
  • 1
  • 1
Ralph
  • 31,584
  • 38
  • 145
  • 282

2 Answers2

16

Generally, the : notation is used for type ascription, forcing the compiler to see a value as some particular type. This is not quite the same as casting.

val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double

In this case, you're ascribing the special varargs type _*. This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses Seq[T]:

def myMethod(params: Any*) = ... //varargs parameter, use as an Array[Any]

val list = Seq("a", 42, 3.14) //a Seq[Any]
myMethod(list : _*)
Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108
Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
7

The ending part : _* converts a collection into vararg parameters.

It looks weird, I know.