Reputation: 1384
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.
Upvotes: 1
Views: 153
Reputation: 42045
There are two things wrong with your code. The first is that you need to use brackets around 1 to 5
, the second is the syntax of your anonymous function. You need brackets around the parameters there.
(1 to 5).foldRight(0)((x,y) => x + y)
Upvotes: -1
Reputation: 108169
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)(_ + _)
Upvotes: 8