What is the Scala syntax for calling a function with variable arguments but with named arguments?

Say I have a function

def f(a:Int = 0, b:String = "", c:Float=0.0, foos: Foo*) { ... } 

Note the use of default arguments for some parameters. Typically, to use the default values, you call a function with named parameters, for example:

 val foo = Foo("Foo!") f(foos = foo) 

This syntax works because I only call a method with one foo . However, if I have two or more

 val foo1 = Foo("Foo!") val foo2 = Foo("Bar!") f(foos = ...) 

It is not so obvious what to feed here. Seq(foo1,foo2) and Seq(foo1,foo2):_* do not print the check.

What else, how can I call it with no foo s?

 // All out of foos! f(foos = ...) 

In this case, calling a function with empty brackets ( f() ) does not work.

Thanks!

+6
source share
2 answers

Given the limitations of Scala 2.9 that Paolo mentioned, you can still use currying to separate parameters in different sections that use named parameters with default arguments, and one for varargs (or multiple argument sections in curry if you want more than one parameter vararg). In terms of readability, the imho result is almost better than using only the named arguments:

 f(b="something")() f(c=3.14)(foo1, foo2) 
+7
source

See the default options in my comment on your question. For how to call a variable part with a named argument, see below (scala 2.9.2):

 scala> case class Foo(a:Int) defined class Foo scala> def f(a:Int, foos: Foo*) = foos.length f: (a: Int, foos: Foo*)Int scala> f(a=2, foos=Foo(2)) res0: Int = 1 // I'm not sure if this is cheating... // am I just naming the first of the two variadic arguments? scala> f(a=2, foos=Foo(2),Foo(3)) res1: Int = 2 //anyway you can do .... scala> f(a=2, foos=Seq(Foo(1), Foo(2)):_*) res2: Int = 2 // with no foos... scala> f(a=2, foos=Nil:_*) res3: Int = 0 
+8
source

All Articles