加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么这个电话隐含含糊不清?

发布时间:2020-12-16 19:08:38 所属栏目:安全 来源:网络整理
导读:TraversableOnce方法的签名如下: def sum[B : A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus) 我可以用它: scala (1 to 10).sumres0: Int = 55 在这种情况下,编译器正在注入Numeric [B]本身,因此在范围内必须有一个明确的隐含值.如果我
TraversableOnce方法的签名如下:

def sum[B >: A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus)

我可以用它:

scala> (1 to 10).sum
res0: Int = 55

在这种情况下,编译器正在注入Numeric [B]本身,因此在范围内必须有一个明确的隐含值.如果我使用Predef.implicitly自己注入,则会发生这种情况:

scala> (1 to 10).sum(implicitly)
<console>:6: error: ambiguous implicit values:
 both method conforms in object Predef of type [A]<:<[A,A]
 and method stringCanBuildFrom in object Predef of type => scala.collection.generic.CanBuildFrom[String,Char,String]
 match expected type T
   (1 to 10).sum(implicitly)
                 ^

为什么这个含糊不清?

我可以使歧义消失

scala> (1 to 10).sum(implicitly[Numeric[Int]])
res2: Int = 55

要么

scala> (1 to 10).sum[Int](implicitly)
res3: Int = 55

我认为这与事实一样,事实上,sum声明一个新的类型参数B>:A(显然是,见下面的编辑),但我仍然困惑为什么在第一个例子中明确地找到了一些东西但不是第二个

编辑 – 解决子项目的内容(下文)

scala> class As[A](as : A*) { 
 | def sum(implicit num : Numeric[A]) : A = as.foldLeft(num.zero)(num.plus) 
 | }
defined class As

scala> (new As(1,2,3,4)).sum
res0: Int = 10

scala> (new As(1,4)).sum(implicitly)
res1: Int = 10

所以,你可以看到隐含的任何调用不是模糊的

解决方法

简短的答案:由于B>:无法推断隐含调用的结果类型.

更长的答案.当定义为隐式的参数缺失时,编译器将搜索当前作用域的任何类型为Numeric [B>:Int]的隐式值,并将使用最具体的 – Numeric [Int].

但是,如果您隐式指定参数(隐式[T](隐含e:T)的调用):T)首先必须解析类型参数T.而scala运行时显然没有这样做.

这跟调用一样:

scala> var f = implicitly
 <console>:5: error: ambiguous implicit values:
 both method conforms in object Predef of type [A]<:<[A,A]
 and method stringCanBuildFrom in object Predef of type =>     scala.collection.generic.CanBuildFrom[String,String]
 match expected type T
       var f = implicitly
               ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读