2

The following does not compile,

def echo(sep: String =" ", s: String*) = s.mkString(sep)

The desired function signature would have a first argument with default value and the rest, any number of strings.

1
  • 2
    So how would you distinguish between a defaulted first arg followed by multiple args, and a specified first arg followed by multiple args ? Commented May 27, 2014 at 11:31

1 Answer 1

6

This is problematic.

Consider this:

echo("a", "b", "c") : is "a" now the seperator or does it belong to s? This cannot be decided by the compiler, since both would work.

A workaround can be to use multiple parameter lists.

def echo(sep: String =" ")(s: String*) = s.mkString(sep)

Now you can use:

echo()("a", "b", "c") //"a b c"
echo("a")("b", "c")   //"bac"
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.