我有一个有点复杂的类型类情况,格式如下:
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] = ???
}
The default
定义被放入LowPriorityTypeClass
具有较低优先级的特征。然而,含糊不清hasOtherTC
对于某些类型仍然会发生S
,显然是因为声明default
比声明更具体hasOtherTC
对于该类型S
.
有没有general确保隐式定义始终比其他定义具有更高/更低优先级的方法? (我的问题不是针对上面的具体代码。)
让我知道发布更完整的示例代码是否有帮助。
请参见为什么会发生这种隐含的歧义行为? https://stackoverflow.com/questions/57933865/why-is-this-implicit-ambiguity-behaviour-happening/包括评论。
引入特质是没有意义的LowPriorityTypeClass
在这种情况下,因为无论如何隐式default
比更具体hasOtherTC
.
没有通用的方法。您可以使用类型类Not
(shapeless.Refute
, implicitbox.Not
) or shapeless.LowPriority
, implicitbox.Priority
或图书馆https://github.com/milessabin/export-hook 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] = ???
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)