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?
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:_*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With