Martin C. Martin
Martin C. Martin

Reputation: 3682

Scala: How do I define an anonymous function with a variable argument list?

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
                          ^

Upvotes: 14

Views: 3345

Answers (1)

michael.kebe
michael.kebe

Reputation: 11085

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

Upvotes: 19

Related Questions