Patrick Steiger
Patrick Steiger

Reputation: 304

Kotlin: extend a dynamically given supertype

Suppose I have the classes:

class A : SuperType() {}

class B : SuperType() {}

class C : B() {}

Suppose I don't want C to extend B() anymore: I want it to extend A(), but now I want A to extend B().

How can I make, on compile-time, A extend B() (or any child of SuperType()) instead of only SuperType()? In other words, how can I make class A declaration generic to accept any child of SuperType()?

Hope it was clear. I'd like to do something like:

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

Upvotes: 0

Views: 606

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

How can I make, on compile-time, A extend B() (or any child of SuperType()) instead of only SuperType()?

You can't. Each class can only extend one fixed superclass.

I think the closest you can get is

class A(x: SuperType): SuperType by x

(See documentation) but this requires SuperType to be an interface instead of a class.

Upvotes: 1

Sergio
Sergio

Reputation: 30605

You can do the following:

open class SuperType {}
open class A(val obj: SuperType) : B() {}
open class B : SuperType() {}
class C : A(B())

or using generics:

open class SuperType {}
open class A<T: SuperType>(val obj: T) : B() {}
open class B : SuperType() {}
class C : A<B>(B())

Upvotes: 0

Related Questions