Accessing static inner class defined in Java, through derived class

感情迁移 提交于 2019-12-01 17:00:47

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!