- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类型类 Search
,它有一个实例 Search[A]
如果我们有 TypeClass1[A]
或 TypeClass2[A]
实例。优先考虑1
实例。
编译如下:
trait TypeClass1[A]
trait TypeClass2[A]
trait Search[A]
object Search extends LPSearch {
implicit def case1[A](implicit ev: TypeClass1[A]): Search[A] = null
}
trait LPSearch {
implicit def case2[A](implicit ev: TypeClass2[A]): Search[A] = null
}
object Test {
implicit val ev1: TypeClass1[Int] = null
implicit val ev2: TypeClass2[Int] = null
implicitly[Search[Int]]
}
case1
, 找到
ev1
, 并停止搜索。
TypeClass2
为了有更多的结构,隐式搜索停止工作:
trait TypeClass1[A]
trait TypeClass2[M[_], A]
trait Search[A]
object Search extends LPSearch {
// This is the same as before
implicit def case1[A](implicit ev: TypeClass1[A]): Search[A] = null
}
trait LPSearch {
implicit def case2[M[_], A](implicit ev: TypeClass2[M, A]): Search[M[A]] = null
}
object Test {
implicit val ev1: TypeClass1[List[Int]] = null
implicit val ev2: TypeClass2[List, Int] = null
// Does not compile:
implicitly[Search[List[Int]]]
}
ambiguous implicit values
, 都说
case1
和
case2
满足条件。
最佳答案
Scala 规范说:
If there are several eligible arguments which match the implicit parameter's type, a most specific one will be chosen using the rules of static overloading resolution.
The relative weight of an alternative
A
over an alternativeB
is a number from 0 to 2, defined as the sum of
- 1 if
A
is as specific asB
, 0 otherwise, and- 1 if
A
is defined in a class or object which is derived from the class or object definingB
, 0 otherwise.
case1
在从定义 case2
的类(特征)派生的对象中定义但反之亦然。case2
与 case1
一样具体但反之亦然。case1
的相对权重在
case2
是 1+0=1 和
case2
的相对权重在
case1
是 0+1=1。所以是歧义。
Error: ambiguous implicit values:
both method case2 in trait LPSearch of type [M[_], A](implicit ev: App.TypeClass2[M,A])App.Search[M[A]]
and method case1 in object Search of type [A](implicit ev: App.TypeClass1[A])App.Search[A]
match expected type App.Search[List[Int]]
implicitly[Search[List[Int]]]
在第二种情况下,使用低优先级特征是没有意义的,因为如果两个隐式都匹配预期类型,
case2
当它们被定义在同一个对象中时是首选。所以试试
object Search {
implicit def case1[A](implicit ev: TypeClass1[A]): Search[A] = null
implicit def case2[M[_], A](implicit ev: TypeClass2[M, A]): Search[M[A]] = null
}
关于scala - 为什么会发生这种隐含的歧义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933865/
我正在使用 Fortran90,但我对它不太熟悉。 在代码的某些地方,我想在 t0 和 tf 之间创建一个由 n 个线性等距点组成的数组,所以我尝试了以下方法: t = t0+(/(i,i=0,n-1
我试图弄清楚为什么在数组构造函数内的 do 构造之前放置标量会产生它所得到的答案。 我一般理解 do 结构,(/(i,i=1,5)/) 相当于 (/1,2,3,4,5/)。 real, dimensi
我目前遇到的情况是,我需要能够通过应用程序 B 的隐式 Intent 广播来启动应用程序 A。应用程序之间没有数据传递。应用程序 A 被简单地启动,显示特定的 Activity。 我的问题是这样的;从
我是一名优秀的程序员,十分优秀!