[英]Abstract parametric types in Scala
我有:
trait A[B[_]]
我有:
trait Base {
type AImpl <: ???
def foo: AImpl
}
这样扩展 Base 的类将定义 A 并实现方法和字段。 IE:
trait BB[T]
trait AA extends A[BB]
trait Child extends Base {
override type AImpl = AA
}
我的问题是声明抽象类型AImpl
。 我试过:
type AImpl <: A[B[_]] forSome {type B[_]}
但我收到以下编译错误:
B[_] takes no type parameters, expected: one
type AImpl <: A[B[_],_] forSome {type B[_]}
声明这种抽象类型的正确方法是什么?
这段代码可以满足您的要求,但我认为您并不是要这样做:
trait A[B[_]]
trait Base {
type AImpl <: A[B] forSome { type B[_] }
def foo: AImpl
}
如果您可以更具体,我可能可以查明您的问题并建议另一种方法。
正如我之前所坚持的,你的意图存在很多问题。 我很清楚你正在尝试做一些你不应该做的事情。
要解释几个问题,您首先需要了解存在类型。 在这里,您使用某些约束来量化AImpl
:
type AImpl <: A[B] forSome { type B[_] }
这就要求它的实现符合这种类型。 然而,这种类型不可能有任何实现,因为
B
隐藏在存在类型内部,因此它在外部是未知的;A
是不变的,所以它强制实现是A[B]
子类型,用于那个确切的隐藏B
。 这两者一起禁止AImpl
实现。 解决方法是转A
协变:
trait A[+B[_]]
trait Base {
type AImpl <: A[B] forSome { type B[_] }
def foo: AImpl
}
trait BB[T]
trait AA extends A[BB]
object Child extends Base {
override type AImpl = A[BB]
def foo = ???
}
这段代码编译没有问题。
然而,再次,我不得不说存在量化B
是一个根本上有缺陷的想法,因为在给定的环境中,没有类型安全的方法来恢复B
了,如果你需要的话,更不用说 Scala 中更高种类的类型是不够的和畸形。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.