对Scala方法调用约定(特别是Seq上的sum函数)感到困惑 [英] Confused about Scala method calling conventions, specifically the sum function on Seq

查看:507
本文介绍了对Scala方法调用约定(特别是Seq上的sum函数)感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的Scala IDE(Eclipse 3.6.2 + Scala IDE 2.0.0 [Scala 2.9.0]),并且尝试执行以下简单操作:

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

那很好,但是最近我也做了很多Groovy,我自动写了:

That works fine, but I've been doing a lot of Groovy also recently and I automatically wrote:

(1 to 10).sum()

第二个版本给我在IDE中的编译器错误,并显示以下消息:

This second version gives me a compiler error in the IDE with the following message:

没有足够的参数表示方法总和:(隐式num:数字[B])B.未指定的值参数编号.

not enough arguments for method sum: (implicit num: Numeric[B])B. Unspecified value parameter num.

我在Scala API上看到sum的两个版本,一个不带参数,另一个带上述隐式.我必须调用不带括号的零参数方法吗?

I see on the Scala API that there are two versions of sum, one that takes no parameters and one that takes the implicit above. Do I have to call zero-argument methods without parentheses?

推荐答案

答案是如果您指定了参数列表(即使用括号),然后,您必须在其中指定参数(或更准确地说,是没有默认值的参数).

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).

如果您省略参数为implicit的非空参数列表上的括号,则编译器可以为您注入它们(假设它可以在您的范围内毫不费力地找到相关的隐式对象:如您的第一个示例)

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

如果您想自己传递参数(在此示例中无需这样做),则可以利用Predef.implicitly,它基本上返回无歧义的范围内隐式值(假设有一个). .它们在这里的用途是:

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)

这在使用多个隐式参数的方法中尤其重要,您可能只希望覆盖其中一个(然后您可以对其他参数使用implicitly).例如,在 scalaz

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

对于有关 scaladoc 用例的问题;这是一个 phantom 条目,向您展示如何将(否则可能引起混淆的)方法与隐式参数列表一起使用.此scaladoc条目的存在可以追溯到

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.

这篇关于对Scala方法调用约定(特别是Seq上的sum函数)感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆