Variable-length argument list with default argument?

Is it possible to set a default argument for a variable length argument list?

Example:

def foo(args: String*) = args.foreach(println) 

How to set default argument for args ?

+7
source share
1 answer

Not. If you try, the compiler will tell you:

error: parameter section with parameter `* 'has no default arguments

But you can achieve the same result when overloading the method:

 class A { def foo(args: String*): Unit = args.foreach(println) def foo(): Unit = foo("A", "B", "C") } 

Here, when you provide the arguments:

 scala> (new A).foo("A", "B") A B 

And here is the "default":

 scala> (new A).foo() A B C 
+12
source

All Articles