Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

scala - Why does leaving the dot out in foldLeft cause a compilation error?

Can anyone explain why I see this compile error for the following when I omit the dot notation for applying the foldLeft function?(version 2.9.2)

scala> val l = List(1, 2, 3)
res19: List[Int] = List(1 ,2 ,3)

scala> l foldLeft(1)(_ * _)
<console>:9: error: Int(1) does not take parameters
                    l foldLeft(1)(_ * _)
                                    ^

but

scala> l.foldLeft(1)(_ * _) 
res27: Int = 6

This doesn't hold true for other higher order functions such as map which doesn't seem to care whether I supply the dot or not.

I don't think its an associativity thing because I can't just invoke foldLeft(1)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because foldLeft is curried. As well as using the dot notation, you can also fix this by adding parentheses:

scala> (l foldLeft 1)(_ * _)
res3: Int = 6

Oh - and regarding your comment about not being able to invoke foldLeft(l), you can, but you need to partially apply it like this:

scala> (l foldLeft 1) _
res3: ((Int, Int) => Int) => Int = <function1>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...