问题描述
我有一些用Java定义的类,类似于下面的代码.我正在尝试通过派生的Java类访问SomeValue
,这在Java中是允许的,但在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
推荐答案
在Kotlin中,嵌套类型和伴随对象不会自动继承.
In Kotlin, nested types and companion objects are not automatically inherited.
此行为不是Java特有的,您可以单独在Kotlin中重现相同的行为:
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.
在Kotlin中,故意将此行为更严格,以避免Java中与通过派生类型访问静态成员/类有关的某些混乱.您还可以看到,当使用派生的类名来引用基类中的静态符号时,很多IDE都会用Java警告您.
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.
关于术语,Kotlin对内部类(即用inner
关键字注释的类)有清晰的定义.并非所有嵌套类都是内部类.另请参见此处.
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.
相关:
- Kotlin - accessing companion object members in derived types
- Kotlin: How can I create a "static" inheritable function?
这篇关于通过派生类访问用Java定义的静态内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!