4

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 invoke 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")

1 Answer 1

15

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}
Sign up to request clarification or add additional context in comments.

1 Comment

I quoted Scala spec to address your concerns. This is basically a language construct built into the compiler. Groovy has a similar operator: f(*a).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.