我想定义一个类继承层次结构,因此参数化方法的参数类型介于我的第一个基类和当前基类之间:
class A { var x; } class B(parent:A = null) extends A { var y; protected def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {} } class C(parent:B = null) extends B { var z protected override def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {} }
这可能吗?是否有任何理由我不应该尝试实现这一点(架构原因或任何其他原因)?
您可以使用>: this.type
类型绑定:
class A class B extends A class C extends B { def method[T >: this.type <: A](a: T) = a } class D extends C
所以你不能C
用类型参数调用方法D
:
scala> new C().method[D](new D) <console>:12: error: type arguments [D] do not conform to method method's type parameter bounds [T >: C <: A] new C().method[D](new D) ^
但您可以使用D
类型参数调用它D
:
scala> new D().method[D](new D) res0: D = D@49df83b5
请注意,任何实例D
也是一个实例C
,因此new C().method(new D)
(没有类型参数)将被编译为new C().method[C](new D)
.