Scala:如何定义带有可变参数列表的匿名函数? [英] Scala: How do I define an anonymous function with a variable argument list?

查看:146
本文介绍了Scala:如何定义带有可变参数列表的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,如何定义一个采用可变数量参数的匿名函数?

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
                          ^

推荐答案

看来这是不可能的.在6.23章匿名函数中的语言规范中. >语法在类型后不允许*.在类型之后的第4.6章函数声明和定义中可以有一个*.

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 *.

但是您可以做的是这

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

这篇关于Scala:如何定义带有可变参数列表的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆