什么:_ *从Scala调用Java vararg方法时做什么? [英] What does :_* do when calling a Java vararg method from Scala?
问题描述
Possible Duplicate:
What does:_*
(colon underscore star) do in Scala?
我正在使用REPL来调用带有Scala数组的Java vararg方法。
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:_*)
我的问题是什么:_ *
吗?它在Scala API中的定义在哪里?
My questions is what does :_*
do? Where is it defined in the Scala API?
推荐答案
添加:_ *
告诉编译器将数组视为varargs。它与Scala和Java一样。如果我有方法
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}
我可以这样称呼:
foo(1, 2, 3, 4) //returns ArrayBuffer(2, 3, 4, 5)
但是如果我想传递一个实际的序列(就像你使用 getMethod
那样)我会这样做:
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:_*)
这篇关于什么:_ *从Scala调用Java vararg方法时做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!