我试图为具有依赖类型的类型类派生一个元组实例。我使用“无形”来为元组元素创建调用类型类。我很难匹配元组实例类型:
import shapeless.the
import simulacrum.typeclass
@typeclass trait Identifiable[M] {
type K
def identify(id: M): K
}
object Identifiable{
implicit def identifiableTuple[K1: Identifiable, K2: Identifiable]: Identifiable[(K1,K2)] = new Identifiable[(K1,K2)]{
val b = the[Identifiable[K2]]
val a = the[Identifiable[K1]]
type K = (a.K, b.K)
override def identify(id: (K1, K2)): K = {
val k1 = the[Identifiable[K1]].identify(id._1)
val k2 = the[Identifiable[K2]].identify(id._2)
(k1,k2)
}
}我知道这个错误:
type mismatch;
found : k1.type (with underlying type ai.fugo.cms.service.common.domain.Identifiable[K2]#K)
required: this.a.K
type mismatch;
found : k2.type (with underlying type ai.fugo.cms.service.common.domain.Identifiable[K1]#K)
required: this.b.K发布于 2020-04-05 15:08:19
尝试Aux模式
trait Identifiable[M] {
type K
def identify(id: M): K
}
object Identifiable {
type Aux[M, K0] = Identifiable[M] { type K = K0 }
implicit def identifiableTuple[M1, K1, M2, K2](
implicit
identifiable1: Identifiable.Aux[M1, K1],
identifiable2: Identifiable.Aux[M2, K2]
): Identifiable.Aux[(M1, M2), (K1, K1)] = new Identifiable[(M1, M2)] {
type K = (K1, K2)
def identify(id: (M1, M2)): (K1, K2) =
identifiable1.identify(id._1) -> identifiable2.identify(id._2)
}
}Aux模式的发明是因为
,
所以,只需使用Aux来派生事物。
https://stackoverflow.com/questions/61044126
复制相似问题