1

In Java you can do this:

class Outer {
    class Inner {
    }
}

class ExtendedClass extends Outer.Inner{
    ExtendedClass(Outer outer) {
        outer.super();
    }
}

So I'd expect in Kotlin you write something like this:

class ExtendedClass(outer: Outer): Outer.Inner(outer: Outer) {
}

Unfortunately this doesn't work.

I know you can do this:

class ExtendedOuter: Outer() {
    inner class ExtendedInner: Inner(){
    }
}

but this forces you to extend the Outer Class which is not always desirable.

This brings me to the question:

Can you extend an inner class in Kotlin, without extending it's outer class? If not, why are we allowed to declare non-open outer classes, when they contain an open inner class?

  • You can extend an open inner class inside its non-open outer class as another inner class. Mostly likely they don’t support the first case you described because it is so rarely needed and violates the principle of least astonishment. – Tenfour04 Mar 25 '22 at 04:46
  • Thanks for the answer. I didn't find any references on how to extend an inner class inside a non-open outer class. Unfortunately IntelliJ's context actions for this specific case result in invalid code. Would you mind showing an example? – Dimidri Sanchez Mar 30 '22 at 08:42
  • I just mean this: `class Outer { open inner class Inner; inner class ExtendedInner: Inner() }` – Tenfour04 Mar 30 '22 at 12:25

0 Answers0