开发者

How to invoke a method taking String * with elements of Array[String]

开发者 https://www.devze.com 2023-04-11 07:19 出处:网络
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\")

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 type S * [...]. Furthermore, the type of e must conform to scala.Seq[T], for some type T which conforms to S. 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}
0

精彩评论

暂无评论...
验证码 换一张
取 消