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

后端 未结 2 966
野趣味
野趣味 2020-12-10 14:31

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)



        
相关标签:
2条回答
  • 2020-12-10 14:52

    Omitting the dot is possible because of scala's syntactic support for the infix notation, which expects 3 parts:

    leftOperand operator rightOperand. 
    

    But because foldLeft had two list of parameters, you end up with 4 parts at the syntactic level: l foldLeft (1) (_ * _)

    Which does not fit infix notation, hence the error.

    0 讨论(0)
  • 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>
    
    0 讨论(0)
提交回复
热议问题