在不参考原始类型的情况下为更高类型的类型召唤 Aux

Summon Aux for higher-kinded type without reference to the original

我正在尝试使用具有更高种类类型的 Aux 模式,并且直到之后才必须指定更高种类的参数。这类似于 中描述的 SO 问题,但有一个显着差异,我将采用相反的方式,即从隐式 def 返回 aux。

// The are types that I want to convert to various things
sealed trait ConversionType
trait CaseA extends ConversionType
object CaseA extends CaseA // In this case, convert to an optional
trait CaseB extends ConversionType
object CaseB extends CaseB // In this case, convert to a future etc...

trait Converter[Prefix] {
  type Paramd[_]
  def create[N](n:N): Paramd[N]
}

// Create the mechanism to convert from the cases, only doing case A for now...
object Converter {
  type Aux[Prefix, Ret[_]] = Converter[Prefix] { type Paramd[_] = Ret[_] }

  // *** Error happens here! ***
  def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

  implicit def makeOptionParamd: Aux[CaseA, Option] =
    new Converter[CaseA] {
      type Paramd[_] = Option[_]
      override def create[N](n:N): Paramd[N] = Option[N](n)
    }
}

// This seems to be fine...
val v = Converter.apply[CaseA].create("test")

我在上面提到的行中得到以下编译错误:

Error:(97, 78) type mismatch;
 found   : p.type (with underlying type Test.this.Converter[Prefix])
 required: Test.Converter.Aux[Prefix,p.Paramd]
    (which expands to)  Test.this.Converter[Prefix]{type Paramd[_] = p.Paramd[_]}
    def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

我做错了什么?

你可能想要的是

object Converter {
  type Aux[Prefix, Ret[_]] = Converter[Prefix] { type Paramd[A] = Ret[A] }

  // compiles
  def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

  implicit def makeOptionParamd: Aux[CaseA, Option] =
    new Converter[CaseA] {
      type Paramd[A] = Option[A]
      override def create[N](n:N): Paramd[N] = Option[N](n)
    }
}

写的时候

type Paramd[_] = Ret[_]

左右两部分的_没有关系。和

一样
type Paramd[A] = Ret[_]

type Paramd[A] = Ret[B] forSome { type B }

所以你定义的Aux[Prefix, p.Paramd]等同于Converter[Prefix] { type Paramd[A] = p.Paramd[_] },而p没有这个类型,因为p.Paramd[A]不是p.Paramd[_]