7

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 ?

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.