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 a default argument for args
?
No. If you try, the compiler will tell you:
error: a parameter section with a `*'-parameter is not allowed to have default arguments
But you can achieve the same result with method overloading:
class A {
def foo(args: String*): Unit = args.foreach(println)
def foo(): Unit = foo("A", "B", "C")
}
Here's when you provide arguments:
scala> (new A).foo("A", "B")
A
B
And here's the "default":
scala> (new A).foo()
A
B
C
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