假设我有以下课程:

class A : SuperType() {}

class B : SuperType() {}

class C : B() {}


假设我不再希望C扩展B():我希望它扩展A(),但是现在我希望A扩展B()

如何在编译时扩展A扩展B()(或SuperType()的任何子级)而不是仅扩展SuperType()?换句话说,如何使类A声明通用以接受SuperType()的任何子代?

希望这很清楚。我想做类似的事情:

class B(whatever_it_receives_as_long_as_child_of_SuperType) : whatever_it_receives_as_long_as_child_of_SuperType()

class C : A(B())    // B is subtype of SuperType so it's ok

最佳答案

如何在编译时使A扩展B()(或SuperType()的任何子代)而不是仅SuperType()?


你不能每个类只能扩展一个固定的超类。

我认为最接近的是

class A(x: SuperType): SuperType by x


(请参见documentation),但这要求SuperType是接口而不是类。

07-24 15:54