Suppose I have a method
def f(s:String *) = s.foreach( x => println(x) )
Now I have an array:
val a = Array("1", "2", "3")
How do I invok开发者_StackOverflow中文版e f
with elements of a
as parameters?
EDIT:
So given a
, I want to do the following:
f(a(0), a(1), a(2)) // f("1", "2", "3")
There is an operator for that:
f(a: _*)
This operation is defined in chapter 4.6.2 Repeated Parameters of The Scala Language Specification Version 2.9 and further explained in 6.6 Function Applications:
The last argument in an application may be marked as a sequence argument, e.g.
e : _*
. Such an argument must correspond to a repeated parameter (§4.6.2) of typeS *
[...]. Furthermore, the type of e must conform toscala.Seq[T]
, for some typeT
which conforms toS
. In this case, the argument list is transformed by replacing the sequence e with its elements.
BTW your f
function can be simplified:
def f(s:String *) = s foreach println
Or better (equals sign is discouraged as it suggests that the method actually returns something, however it "only" return Unit
):
def f(s:String *) {s foreach println}
精彩评论