Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a default argument for args ?

like image 653
John Threepwood Avatar asked Sep 01 '12 17:09

John Threepwood


1 Answers

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
like image 96
dhg Avatar answered Sep 22 '22 20:09

dhg