How to call a method that accepts String * with array elements [String]

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 call f with a elements as parameters?

EDIT:

So given a , I want to do the following:

 f(a(0), a(1), a(2)) // f("1", "2", "3") 
+4
source share
1 answer

There is an operator for this:

 f(a: _*) 

This operation is defined in chapter 4.6.2 Duplicate Scala parameters. The language specification version 2.9 and further is explained in 6.6 Function assignments:

The last argument in the application can be marked as a sequence argument, for example. e : _* . Such an argument shall correspond to a repeated parameter (Section 4.6.2) of type S * [...]. In addition, type e must match scala.Seq[T] for some type T , which corresponds to S In this case, the argument list is converted by replacing the sequence e with its elements.


By the way, your f function can be simplified:

 def f(s:String *) = s foreach println 

Or better (an equal sign is not recommended, since it assumes that the method actually returns something, however it only returns Unit ):

 def f(s:String *) {s foreach println} 
+15
source

All Articles