Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple brackets in function invocation

Tags:

scala

I'm a bit confused by this Scala notation:

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

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

like image 560
pistacchio Avatar asked Mar 13 '26 07:03

pistacchio


1 Answers

Scala allows you to have multiple arguments list:

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

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)

you can write just

List(1, 2, 3).foldLeft(0)((x, acc) => acc+x)
like image 195
om-nom-nom Avatar answered Mar 15 '26 05:03

om-nom-nom