开发者

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开发者_C百科?

scala> def foo = (blah:Int*) => 3
<console>:1: error: ')' expected but identifier found.
       def foo = (blah:Int*) => 3
                          ^


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜