Can't compile generic nested inner sealed class


#1

This snippet fails to compile (in IntelliJ IDEA 2016.3) under Kotlin 1.0.6-release-127:

class Outer<T> {
    inner sealed class Inner {
        object Obj : Inner()
        inner class Cls(val data: T?) : Inner()
    }
    val empty = Inner.Cls(null)
}

The error is “Unresolved reference: Cls” pointing to line 6 (val empty = …). Is this valid Kotlin?

Eliminating the type variable T give us this:

class Outer {
    sealed class Inner {
        object Obj : Inner()
        class Cls(val data: Any?) : Inner()
    }
    val empty = Inner.Cls(null)
}

which compiles without error. Am I missing something, or is this a bug?

Update: Kotlin version 1.1.0-beta-38 gives the same error.


Sealed inner classes
#2

Thank you for your report!

Generally, the compiler error is correct: as Cls is an inner class, you can’t just create it without an instance of Inner class.
Of course, diagnostic message might be more informative (see the issue)
Inner().Cls(null) might help, but here Inner is sealed, thus in some sense, it behaves like an abstract, i.e. it can’t be
instantiated itself.

I see several problems in your code that might be a compiler issue:

  1. An object inside inner classes must be an error too (KT-16232)
  2. inner sealed classes may be a subject to prohibit them (KT-16233)

By the way, the second example works only because it doesn’t contain inner classes (only nested ones, no inner modifier)


#3

Thanks! The bug reports were helpful, and I’ve solved my problem without using inner classes.