问题描述
假设我有以下课程:
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
1楼
如何在编译时使A扩展B()(或SuperType()的任何子代)而不是仅SuperType()?
你不能 每个类只能扩展一个固定的超类。
我认为最接近的是
class A(x: SuperType): SuperType by x
(请参阅 ),但这要求SuperType是接口而不是类。
2楼
您可以执行以下操作:
open class SuperType {}
open class A(val obj: SuperType) : B() {}
open class B : SuperType() {}
class C : A(B())
或使用泛型:
open class SuperType {}
open class A<T: SuperType>(val obj: T) : B() {}
open class B : SuperType() {}
class C : A<B>(B())