27

Possible Duplicate:
What does :_* (colon underscore star) do in Scala?

I’m using the REPL to call a Java vararg method with a Scala Array.

I get an error if I do this:

case class Person(name: String, age: Int)
val array = Array(classOf[String], classOf[Int])
Person.getClass.getMethod("apply", array)

But if I do this then it works:

Person.getClass.getMethod("apply", array:_*)

My questions is what does :_* do? Where is it defined in the Scala API?

Community
  • 1
  • 1
Matt Roberts
  • 1,107
  • 10
  • 15
  • Not sure if it's exactly a duplicate. Note that he calls a Java method with the repeated parameter ascription, not a Scala repeated-params method. – axel22 Jun 20 '12 at 18:46
  • 2
    Stack Overflow does a lousy job at searching symbols -- in fact, it completely ignores them. If you need to search for symbols in the future, use [Symbol Hound](http://symbolhound.com/). It will search for questions on Stack Overflow but keep the symbols. – Daniel C. Sobral Jun 20 '12 at 19:32

1 Answers1

37

adding :_* tells the compiler to treat the array as varargs. It works the same with Scala as with Java. If I have a method

def foo(args: Int*) = args.map{_ + 1}

I can call it as such:

foo(1, 2, 3, 4) //returns ArrayBuffer(2, 3, 4, 5)

but if I want to pass an actual sequence to it (as you are with getMethod) I would do:

val mylist = List(1, 2, 3, 4)
foo(mylist:_*)
Dan Simon
  • 12,891
  • 3
  • 49
  • 55