Accessing static inner class defined in Java, through derived class

后端 未结 1 870
生来不讨喜
生来不讨喜 2021-01-18 12:36

I\'ve got some classes defined in java, similar to the code below. I\'m trying to access SomeValue through a derived java class, which is allowed in java, but n

相关标签:
1条回答
  • 2021-01-18 13:13

    In Kotlin, nested types and companion objects are not automatically inherited.

    This behavior is not specific to Java, you can reproduce the same behavior in Kotlin alone:

    open class Base {
        class Nested
    }
    
    class Derived : Base()
    
    val base = Base.Nested::class        // OK
    val derived = Derived.Nested::class  // Error: 'Nested' unresolved
    

    As such, you explicitly have to qualify the nested class using the base class.

    This behavior was deliberately made more strict in Kotlin, to avoid some of the confusion in Java related to accessing static members/classes via derived types. You also see that a lot of IDEs warn you in Java when you use a derived class name to refer to static symbols in the base class.

    Regarding terminology, Kotlin has a clear definition of inner classes (namely those annotated with the inner keyword). Not all nested classes are inner classes. See also here.

    Related:

    • Kotlin - accessing companion object members in derived types
    • Kotlin: How can I create a "static" inheritable function?
    0 讨论(0)
提交回复
热议问题