1

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.

sirksel
  • 747
  • 6
  • 19

1 Answers1

3

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.

Sonu Sourav
  • 2,926
  • 2
  • 12
  • 25
ice1000
  • 6,406
  • 4
  • 39
  • 85
  • You're right. I should have said **outside of A**. [Here's the particular use case I'm trying to solve](https://stackoverflow.com/questions/47361279), which was a sealed class originally. A is really a quasi-interface, and A1 and A2 are boxed foreign classes I don't control. Could you give a read and maybe answer there too if you have ideas? Thanks. – sirksel Nov 20 '17 at 04:19
  • Please mention that you just need to construct the inner class with an instance of the outer class. Maybe you should write a function in the outer class that returns the instance of the inner class. – ice1000 Nov 20 '17 at 06:27