How to create an instances for typeclass with dependent type using shapeless

前端 未结 2 986
情深已故
情深已故 2021-01-21 17:18

I\'m trying to derive a tuple instance for a type class with dependent type. I\'m using shapeless to create summon the type class for the tuple elements. I\'m having trouble mat

2条回答
  •  面向向阳花
    2021-01-21 17:44

    Try Aux pattern

    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 pattern was invented because

    • it is easier for human to read it
    • I think(?) compiler used to have problems with deriving type classes for path-dependent types... but not for their aliases

    So just use Aux to derive things.

提交回复
热议问题