函数调用中的多个括号 [英] Multiple brackets in function invocation

查看:40
本文介绍了函数调用中的多个括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个 Scala 表示法有点困惑:

I'm a bit confused by this Scala notation:

List(1, 2, 3).foldLeft(0)((x, acc) => acc+x)

0"和函数都是foldLeft的参数,为什么它们在两个相邻的括号组中传递?我希望它可以工作:

Both "0" and the function are arguments for foldLeft, why are they passed in two adjacent brackets groups? I'd aspect this to work:

List(1, 2, 3).foldLeft(0, ((x, acc) => acc+x))

但事实并非如此.谁能向我解释一下?另外,如何以及为什么声明这种类型的函数?谢谢

But it doesn't. Can anyone explain this to me? Also, how and why to declare such a type of function? Thanks

推荐答案

Scala 允许你有多个参数列表:

Scala allows you to have multiple arguments list:

def foo(a: Int)(b: String) = ???
def bar(a: Int)(b: String)(c: Long) = ???

foldLeft 使用这种语法的原因是编译器进行类型推断的方式:已经推断出前一组参数中的类型,用于推断连续参数组中的类型.在 foldLeft 的情况下,它允许您删除 (x, acc) 旁边的类型归属,而不是:

The reason for using such syntax for foldLeft is the way compiler does type inference: already inferred types in the previous group of arguments used to infer types in consecutive arguments group. In case of foldLeft it allows you to drop type ascription next to the (x, acc), so instead of:

List(1, 2, 3).foldLeft(0)((x: Int, acc: Int) => acc+x)

你可以只写

List(1, 2, 3).foldLeft(0)((x, acc) => acc+x)

这篇关于函数调用中的多个括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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