Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does :_* do when calling a Java vararg method from Scala? [duplicate]

Tags:

java

scala

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?

like image 832
Matt Roberts Avatar asked Jun 20 '12 18:06

Matt Roberts


1 Answers

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:_*)
like image 72
Dan Simon Avatar answered Nov 19 '22 02:11

Dan Simon