I am working with type classes and have problems auto-deriving them for types that unrelatedly extends extra (marker/indicator) traits. It is hard to explain, but this minimal example should make it clear what I mean:
// 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
}
(I get the same behaviour if I make Plentiful
universal and/or add a self-type of Food
to it.)
Investigating the implicit-log from compilation, I find this:
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]]
It seems to me that type inference on F1 is breaking down, as ignoreSupply
is simply not tried out using the right types when the compiler is looking for a IsHarmfulToEat[Cake with Plentiful]
. Can anyone explain to me why that is? And/or how to guide the compiler to try the right type? And/or to achieve the ignoreSupply rule in another way?