Scala strange error when using foldRight with operator syntax

advertisements
1 to 5 foldRight (0)(x:Int, y:Int => x+y)

I am trying to add all the values from right to left with 0 as the initial parameter. I get the following error

Int(0) does not take parameters

Can anyone explain to me what this error even means? Thanks.


It's just the parser getting "confused", so it's trying to apply (x: Int, y: Int ...) as argument of (0).

Specifically, what you're using is a scala syntactic feature that allows to use

a.f(b)

as

a f b

This works with any method that has a single parameter. However when your method has multiple parameter lists (like foldRight), you have to use extra care.

This is what the parser sees

1 to 5  foldRight (0)(x: Int, y: Int => x + y)
|__a__| |___f___| |____________b_____________|

So when evaluating b, it treats 0 as a function with (x: Int, ...) as an argument. Clearly this can't work, because "Int(0) does not take parameters".

Instead, you can use

(1 to 5).foldRight(0)((x,y) => x + y)

or even

(1 to 5).foldRight(0)(_ + _)