我正在使用类型类,但在自动将它们派生为不相关地扩展了额外(标记/指示符)特征的类型时遇到了问题。很难解释,但是这个最小的例子应该清楚我的意思:
// Base type we are working on
trait Food {}
// Marker trait - unrelated to Food's edibility
trait Plentiful {}
// Indicator type class we want to derive
trait IsHarmfulToEat[F<:Food] {}
object IsHarmfulToEat {
// Rule that says that if some food is harmful to eat,
// an enormous amount is so as well
implicit def ignoreSupply[F1<:Food,F2<:F1 with Plentiful]
(implicit isHarmful: IsHarmfulToEat[F1],
constraint: F2=:=F1 with Plentiful): IsHarmfulToEat[F2] =
new IsHarmfulToEat[F2]{}
}
// Example of food
case class Cake() extends Food {}
object Cake {
// Mark Cake as being bad for you
implicit val isBad: IsHarmfulToEat[Cake] = new IsHarmfulToEat[Cake] {}
}
object FoodTest extends App {
// Our main program
val ignoreSupplyDoesWork: IsHarmfulToEat[Cake with Plentiful] =
IsHarmfulToEat.ignoreSupply[Cake,Cake with Plentiful] // compiles fine
val badCake = implicitly[IsHarmfulToEat[Cake]] // compiles fine
val manyBadCakes = implicitly[IsHarmfulToEat[Cake with Plentiful]]
// ^^^ does not compile - I do not understand why
}
(如果我使
Plentiful
通用和/或向其添加自类型的Food
,我将得到相同的行为。)从编译调查隐式日志,我发现:
Food.scala:33: util.this.IsHarmfulToEat.ignoreSupply is not a valid implicit value for IsHarmfulToEat[F1] because:
hasMatchingSymbol reported error: diverging implicit expansion for type IsHarmfulToEat[F1]
starting with method ignoreSupply in object IsHarmfulToEat
val manyBadCakes = implicitly[IsHarmfulToEat[Cake with Plentiful]]
^
Food.scala:33: util.this.IsHarmfulToEat.ignoreSupply is not a valid implicit value for IsHarmfulToEat[Cake with Plentiful] because:
hasMatchingSymbol reported error: diverging implicit expansion for type IsHarmfulToEat[F1]
starting with method ignoreSupply in object IsHarmfulToEat
val manyBadCakes = implicitly[IsHarmfulToEat[Cake with Plentiful]]
^
Food.scala:33: diverging implicit expansion for type IsHarmfulToEat[Cake with Plentiful]
starting with method ignoreSupply in object IsHarmfulToEat
val manyBadCakes = implicitly[IsHarmfulToEat[Cake with Plentiful]]
在我看来,F1上的类型推断正在崩溃,因为在编译器寻找
ignoreSupply
时,只是没有使用正确的类型尝试IsHarmfulToEat[Cake with Plentiful]
。谁能向我解释为什么?和/或如何引导编译器尝试正确的类型?和/或以另一种方式实现ignoreSupply规则? 最佳答案
如果使IsHarmfulToEat
变反,则以下代码编译
trait Food
trait Plentiful
trait IsHarmfulToEat[-F <: Food]
object IsHarmfulToEat {
implicit def ignoreSupply[F <: Food]
(implicit isHarmful: IsHarmfulToEat[F]
): IsHarmfulToEat[F with Plentiful] =
new IsHarmfulToEat[F with Plentiful]{}
}
case class Cake() extends Food {}
object Cake {
implicit val isBad: IsHarmfulToEat[Cake] = new IsHarmfulToEat[Cake] {}
}
object FoodTest extends App {
val ignoreSupplyDoesWork: IsHarmfulToEat[Cake with Plentiful] =
IsHarmfulToEat.ignoreSupply[Cake]
val badCake = implicitly[IsHarmfulToEat[Cake]]
val manyBadCakes = implicitly[IsHarmfulToEat[Cake with Plentiful]]
}