假设我有以下内容:
class Bounded[A] {
type apply[C <: A] = C
}
这段代码可以编译:
implicitly[Bounded[Any]#apply[String] =:= String]
这个失败了:
type Str = Bounded[Any]#apply[String]
使用以下内容:
[error] /home/grant/Workspace/scunits/test/src/main/scala/Box.scala:37: type arguments[String] do not conform to type apply's type parameter bounds [C <: A]
[error] type Str = Bounded[Any]#apply[String]
[error] ^
我尝试使用抽象类型替代类型参数,但结果相同。我找到的唯一解决方法是实例化该类型。以下代码可以编译:
val boundedAny = new Bounded[Any]
type Str2 = boundedAny.apply[String]
很不幸,我正在使用幽灵类型进行编程,这些类型通常由于性能原因没有运行时实例。
为什么Scala在这里产生了一个编译错误?是否有更好的解决方法?
感谢任何帮助。
更新:除了下面的解决方法,我还需要一种覆盖具有抽象类型界限的类型的方法。我是这样做的:
object Test {
class AbstractBounded[A] {
type apply[C <: A] <: A
class Workaround[C <: A] {
type go = apply[C]
}
}
class Bounded[A] extends AbstractBounded[A] {
type apply[C <: A] = C
}
type Str = Bounded[Any]#Workaround[String]#go
}