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

查看:27
本文介绍了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天全站免登陆