Accessing static inner class defined in Java, through derived class

kec*_*ccs 6 java interop kotlin

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 not in kotlin.

Is there a way to access the field through the derived class?

// java file
// -------------------------------------------------

class MyBaseClass {
    public static final class MyInnerClass
    {
        public static int SomeValue = 42;
    }
}

final class MyDerivedClass extends MyBaseClass {
}

// kotlin file
// -------------------------------------------------

val baseAccess = MyBaseClass.MyInnerClass.SomeValue;
// this compiles

val derivedAccess = MyDerivedClass.MyInnerClass.SomeValue;
//                                 ^ compile error: Unresolved reference: MyInnerClass

Run Code Online (Sandbox Code Playgroud)

The*_*tor 4

在 Kotlin 中,嵌套类型和伴生对象不会自动继承。

此行为并非 Java 所特有,您可以单独在 Kotlin 中重现相同的行为:

open class Base {
    class Nested
}

class Derived : Base()

val base = Base.Nested::class        // OK
val derived = Derived.Nested::class  // Error: 'Nested' unresolved
Run Code Online (Sandbox Code Playgroud)

因此,您必须明确地使用基类来限定嵌套类。

Kotlin 中故意使这种行为更加严格,以避免 Java 中与通过派生类型访问静态成员/类相关的一些混乱。您还发现,当您使用派生类名称引用基类中的静态符号时,许多 IDE 会在 Java 中向您发出警告。

关于术语,Kotlin 对内部类(即用关键字注释的内部类)有明确的定义inner。并非所有嵌套类都是内部类。另请参阅此处

有关的: