Say I have a function
def f(a:Int = 0, b:String = "", c:Float=0.0, foos: Foo*) { ... }
Notice the use of default arguments for some parameters. Typically, to make use of default values, you invoke a function with named parameters like so:
val foo = Foo("Foo!")
f(foos = foo)
This syntax works because I'm only invoking the method with one foo
. However, if I have two or more
val foo1 = Foo("Foo!")
val foo2 = Foo("Bar!")
f(foos = ...)
it's not so obvious what should be fed in here. Seq(foo1,foo2)
and Seq(foo1,foo2):_*
do not type check.
What's more, how can I call it with no foo
s?
// All out of foos!
f(foos = ...)
For this case, calling the function with empty parentheses (f()
) does not work.
Thanks!
For the default parameters, see my comment to your question. For how to call the variadic 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With