在类型细化中使用类型构造函数

Using a type constructor in a type refinement

我遇到的问题可能最好用代码表达 - 下面是一个简化的示例:

abstract class MainTC[A] {
  type E
  // A type constructor for the implementing type:
  type CN[_]  
  implicit val ev: CN[A] =:= A  // check that CN works as a type constructor for A
  def get(self: A): E
  def set[B](self: A, other: B): CN[B] { type E = B }
  def convert[B](self: A)(implicit conv: Convert[A, E, B]) = conv.convert(self)(this)
}

abstract class Convert[A, _E, B] {
  type Out
  def convert(self: A)(implicit isMain: MainTC[A] { type E = _E }): Out 
}
object Convert {
  implicit def convertDoubleToInt[A, _CN[_]](implicit 
    isMain: MainTC[A] { type E = Double; type CN[_] = _CN[_] },
  ): Convert[A, Double, Int] = new Convert[A, Double, Int] {
    type Out = _CN[Int] { type E = Int }
    def convert(self: A): Out = {
      val toInt = isMain.get(self).toInt
      isMain.set[Int](self, toInt)
      // type mismatch - 
      // found: isMain.CN[Int]{type E = Int} (which expands to) _CN[_]{type E = Int}
      // required: this.Out (which expands to) _CN[Int] {type E = Int}
    }
  }
}

这里的基本情况很简单——我正在使用类型类来实现多态 convert 函数。棘手的部分是我将类型构造函数存储为 MainTC 类型类中的抽象类型。在 Convert 类型类中进行转换时,我想使用该类型构造函数创建一个新类型作为输出类型(例如,CN[Int])。我正在尝试使用 Aux 模式之类的东西来实现这一点,_CN[_] 被创建为 isMain.CN[_] 的类型别名。但是,它不起作用(代码中的错误消息)。如果有人能帮助我,我将不胜感激。

你是说 type CN[_] = _CN[_] 还是 type CN[X] = CN[X]?如果你把它改成后者,你 运行 变成

的问题
def convert(self: A): Out

无法实施

def convert(self: A)(implicit isMain: MainTC[A] { type E = _E }): Out

因为它缺少隐式参数。请记住,Scala 隐式不必是连贯的:convertDoubleToInt(isMain: MainTC[A] {type E = _ E}).TCconvert(isMain: MainTC[A] {type E = _ E}).TC

不同