Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In scala can I pass repeated parameters to other methods?

Here is something I can do in java, take the results of a repeated parameter and pass it to another method:

public void foo(String ... args){bar(args);} public void bar(String ... args){System.out.println("count="+args.length);} 

In scala it would look like this:

def foo(args:String*) = bar(args) def bar(args:String*) = println("count="+args.length) 

But this won't compile, the bar signature expects a series of individual strings, and the args passed in is some non-string structure.

For now I'm just passing around arrays. It would be very nice to use starred parameters. Is there some way to do it?

like image 342
Fred Haslam Avatar asked May 14 '10 16:05

Fred Haslam


People also ask

What does _* mean in Scala?

: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs. It is completely valid to create a Queue using Queue.

How do you pass variables in Scala?

Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array[String].

Is Scala pass by value or reference?

Java and Scala both use call by value exclusively, except that the value is either a primitive or a pointer to an object.

What is Varargs in Scala?

Most of the programming languages provide us variable length argument mobility to a function, Scala is not a exception. it allows us to indicate that the last argument of the function is a variable length argument. it may be repeated multiple times.


1 Answers

Java makes an assumption that you want to automatically convert the Array args to varargs, but this can be problematic with methods that accept varargs of type Object.

Scala requires that you be explicit, by ascribing the argument with : _*.

scala> def bar(args:String*) = println("count="+args.length) bar: (args: String*)Unit  scala> def foo(args:String*) = bar(args: _*) foo: (args: String*)Unit  scala> foo("1", "2") count=2 

You can use : _* on any subtype of Seq, or on anything implicitly convertable to a Seq, notably Array.

scala> def foo(is: Int*) = is.length foo: (is: Int*)Int  scala> foo(1, 2, 3) res0: Int = 3  scala> foo(Seq(1, 2, 3): _*) res1: Int = 3  scala> foo(List(1, 2, 3): _*) res2: Int = 3  scala> foo(Array(1, 2, 3): _*) res3: Int = 3  scala> import collection.JavaConversions._ import collection.JavaConversions._  scala> foo(java.util.Arrays.asList(1, 2, 3): _*) res6: Int = 3 

It is explained well with examples in the Language Reference, in section 4.6.2.

Note that these examples are made with Scala 2.8.0.RC2.

like image 115
retronym Avatar answered Oct 13 '22 07:10

retronym