确保隐式定义始终具有更高/更低优先级的一般方法 [英] General way of ensuring implicit definition always has higher/lower priority
问题描述
我有一个有点复杂的类型类情况,格式如下:
I have a somewhat complex typeclass situation in the following format:
sealed trait TypeClass[S <: MyType] {
type Out <: MyType
}
sealed trait LowPriorityTypeClass {
// Case: OtherTypeClass is NOT defined for the input type S.
// The output type is the same as the input type.
implicit def default[S <: MyType]: TypeClass.Aux[S, S] = ???
}
object TypeClass extends LowPriorityTypeClass {
type Aux[S <: MyType, O <: MyType] = TypeClass[S] { type Out = O }
// Case: OtherTypeClass is defined for the input type S.
// The output type is the same as in the OtherTypeClass definition.
implicit def hasOtherTC[S <: MyType, O <: MyType](
implicit otherTC: OtherTypeClass.Aux[S, O],
): TypeClass.Aux[S, O] = ???
}
default
定义被放在 LowPriorityTypeClass
trait 中,目的是降低优先级.然而,hasOtherTC
的歧义仍然发生在某些类型 S
上,显然是因为 default
的声明比 的声明更具体hasOtherTC
用于该类型 S
.
The default
definition was put in the LowPriorityTypeClass
trait with the intention of having a lower priority. However, an ambiguity with hasOtherTC
still happens for some type S
, apparently because the declaration of default
is more specific than the declaration of hasOtherTC
for that type S
.
是否有一种通用方法来确保隐式定义始终比其他定义具有更高/更低的优先级?(我的问题不是针对上面的具体代码.)
Is there a general way to ensure that an implicit definition will always have a higher/lower priority than other definition? (My question is not for the specific code above.)
如果发布更完整的示例代码会有所帮助,请告诉我.
Let me know if posting a more complete sample code would help.
推荐答案
请参阅 为什么会发生这种隐含的歧义行为? 包括评论.
在这种情况下引入特征LowPriorityTypeClass
是没有意义的,因为无论如何隐式default
比hasOtherTC
更具体.
There is no sense in introducing trait LowPriorityTypeClass
in this case because anyway implicit default
is more specific than hasOtherTC
.
没有通用的方法.您可以使用类型类 Not
(shapeless.Refute
, implicitbox.Not
) 或 shapeless.LowPriority
, implicitbox.Priority
或库 https://github.com/milessabin/export-hook.
There is no general way. You can use type classes Not
(shapeless.Refute
, implicitbox.Not
) or shapeless.LowPriority
, implicitbox.Priority
or library https://github.com/milessabin/export-hook.
object TypeClass {
type Aux[S <: MyType, O <: MyType] = TypeClass[S] {type Out = O}
implicit def hasOtherTC[S <: MyType, O <: MyType](implicit
otherTC: OtherTypeClass.Aux[S, O]
): TypeClass.Aux[S, O] = ???
implicit def default[S <: MyType](implicit
noOtherTC: Refute[OtherTypeClass[S]]
): TypeClass.Aux[S, S] = ???
}
这篇关于确保隐式定义始终具有更高/更低优先级的一般方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!