sirksel
sirksel

Reputation: 787

Inner class within its abstract superclass in Kotlin?

If a set of inner classes are the only implementations (subclasses) of their outer abstract containing class, how does one instantiate them?

abstract class A {
    inner class A1 : A()
    inner class A2 : A()
}

In other words, what is the syntax to construct an instance of A1 or A2?

EDIT: ... outside the body of class A.

Upvotes: 2

Views: 1617

Answers (1)

ice1000
ice1000

Reputation: 6569

Are you looking for this?

abstract class A {
    fun doSome() { // OK
        val a1 = A1()
        val a2 = A2()
    }
    inner class A1 : A()
    inner class A2 : A()
}

I think you probably want to construct instances of A1/A2 outside of A, like:

abstract class A {
    inner class A1 : A()
    inner class A2 : A()
}
fun doSome() { // Error
    val a1 = A1()
    val a2 = A2()
}

This is not allowed in both Kotlin and Java, because the inner class holds pointers to the outer class. If you want to construct A1/A2 outside of A, simply remove the inner modifiers.

abstract class A {
    class A1 : A()
    class A2 : A()
}

fun doSome() { // OK
    val a1 = A.A1()
    val a2 = A.A2()
}

Also, in addition, since you said it's

a set of inner classes are the only implementations (subclasses) of their outer abstract containing class

You can replace abstract modifier with sealed. This will help Kotlin do exhautiveness check in when expression.

Upvotes: 3

Related Questions