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

前端 未结 2 2122
夕颜
夕颜 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:49

    The answer is that if you specify a parameter list (i.e. use the parens), then you must specify the parameters in it (or, more accurately, those without defaults).

    If you omit the parens on a non-empty parameter list whose parameters are implicit, then the compiler can inject them for you (assuming it can find the relevant implicits unabmiguously in your scope: as in your first example)

    1 to 10 sum
    

    If you want to pass in the parameter yourself (there is no need to do so in this example), then you can take advantage of Predef.implicitly which basically returns the unabiguous in-scope implicit value (assuming there is one). Their use here would be:

    (1 to 10).sum(implicitly[Numeric[Int]])
    (1 to 10).sum[Int](implicitly)
    

    This is particularly important in methods which take more than one implicit parameter, of which you might only wish to override one (you can then use implicitly for the others). For example, in scalaz

    aFoldable.sum(implicitly, myMonoid) //uses implicit Foldable but bespoke monoid
    

    For your question about the scaladoc use case; this is a phantom entry to show you how to use the (otherwise potentially confusing) method with the implicit parameter list. The existence of this scaladoc entry can be traced to this notorious question.

提交回复
热议问题