14

In Scala, how do I define an anonymous function which takes a variable number of arguments?

scala> def foo = (blah:Int*) => 3
<console>:1: error: ')' expected but identifier found.
       def foo = (blah:Int*) => 3
                          ^
Martin C. Martin
  • 3,565
  • 3
  • 29
  • 36

1 Answers1

19

It looks like this is not possible. In the language specification in chapter 6.23 Anonymous functions the syntax does not allow an * after a type. In chapter 4.6 Function Declarations and Definitions after the type there can be an *.

What you can do however is this:

scala> def foo(ss: String*) = println(ss.length)
foo: (ss: String*)Unit

scala> val bar = foo _
bar: (String*) => Unit = <function1>

scala> bar("a", "b", "c")
3

scala> bar()
0
michael.kebe
  • 10,916
  • 3
  • 44
  • 62
  • 2
    This doesn't work for me in Scala 2.12: :13: error: too many arguments (3) for method apply: (v1: Seq[String])Unit in trait Function1 – UnitasBrooks Aug 01 '19 at 16:24