Confused about Scala method calling conventions, specifically the sum function on Seq

前端 未结 2 2121
夕颜
夕颜 2021-02-19 05:11

I was playing around with the new Scala IDE (Eclipse 3.6.2 + Scala IDE 2.0.0 [Scala 2.9.0]) and I tried to do something simple like this:

(1 to 10).sum
         


        
2条回答
  •  余生分开走
    2021-02-19 05:43

    There is only one version. If you carefully look at the API, the entry that has no parentheses says "[use case]" in the beginning. This is a synthetic duplicate entry in the API docs which is for easier grasping; the use-case entries are basically reduced full entries for some common scenarios. More on this in this question: Scaladoc [use case]

    The reason why the second call (...sum()) fails is that although the argument is implicit, it doesn't have a default value. You can only omit arguments inside parentheses when default values are provided. Although this sounds illogical, implicit arguments are treated differently: either you supply them explicitly, then you need to use the parentheses, or you omit them (because an implicit is found in scope), but then you also need to drop the parentheses. This is to facilitate better readability, e.g.

    def test(fun: Int => Int)(implicit s: String)
    

    now you can write test { i => i } and not test(i => i)() which is awkward.

提交回复
热议问题