【发布时间】:2020-10-28 20:25:25
【问题描述】:
我遇到的问题可能最好用代码来表达 - 下面是一个简化示例:
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[_] 的类型别名。但是,它不起作用(代码中的错误消息)。如果有人能帮我一把,我将不胜感激。
【问题讨论】: