Scala 中函数对象的可变参数错误? [英] Error with varargs for function-objects in Scala?

查看:32
本文介绍了Scala 中函数对象的可变参数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

val f = (args: Int*) => args.sum

error: ')' expected but identifier found.
val f = (args: Int*) => args.sum
                  ^

然而这工作得很好

def sum(args: Int*) = args.sum
val f = sum _

也是这样

val f: (Int*) => Int = args => args.sum

顺便说一句.我正在使用 Scala 2.9.1

btw. I'm using scala 2.9.1

推荐答案

我不是阅读规范的专家,但看起来匿名函数不支持 varargs 语法.

I'm not an expert in specification reading, but it looks like the varargs Syntax is not supported for anonymous function.

比较 语言规范

ParamType ::= Type
              | ‘=>’ Type
              | Type ‘*’

6.23 匿名函数

Binding ::= (id | ‘_’) [‘:’ Type]

我不知道这是什么原因.似乎有原因,但没有一个可以轻易解释.Martin Odersky 评论了为匿名函数添加可变参数的请求:这起初看起来很诱人,但它会带来很多复杂性(你只需要相信我就可以了)."

I have no idea what the reasons for that though. There seem to be reasons but none that can easily be explained. Martin Odersky commented on a request to add varargs for anonymous functions: "This looks tempting at first, but it would drag in a lot of complexity (you just need to believe me on that one)."

这篇关于Scala 中函数对象的可变参数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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