英文:
How to access an enum member of a Java interface using Kotlin?
问题
I have a Java interface, and need to access it through my Kotlin application. But it is not working.
// On Java
public interface IMyInterface {
int TEST_OK = 1;
enum MyEnum {
NOK(0),
OK(1);
private int val;
MyEnum(int val) {
this.val = val;
}
}
}
public final class MyClass implements IMyInterface {
...
}
// And on Kotlin
MyClass.TEST_OK // Works
MyClass.MyEnum.OK // Does not work (Unresolved reference)
IMyInterface.MyEnum.OK // Works
Any lighting?
英文:
I have a Java interface, and need to access it throught my Kotlin application. But it is not working.
// On Java
public interface IMyInterface {
int TEST_OK = 1;
enum MyEnum {
NOK(0),
OK(1);
private int val;
MyEnum(int val) {
this.val = val;
}
}
public final class MyClass implements IMyInterface {
...
}
// And on Kotlin
MyClass.TEST_OK // Works
MyClass.MyEnum.OK // Does not work (Unresolved reference)
IMyInterface.MyEnum.OK // Works
Any lighting?
答案1
得分: 2
实现接口不会直接给实现类访问接口的静态成员的权限,比如隐式静态的 int TEST_OK
或者静态内部类 MyEnum
。
在Java中,静态成员属于一个与类或接口同名的类对象,并且会被单独处理。实现接口的行为与该接口的任何静态成员完全独立。
我怀疑这可能是Kotlin的设计者没有延续静态成员概念的原因之一,而是用伴生对象来取而代之。类与包含所有静态成员的类对象的概念会引起混淆。
英文:
Implementing an interface does not give the implementing class direct access to the interface's static members like the implicitly static int TEST_OK
or the static inner class MyEnum
.
In Java, static members belong to a class object with the same name as the class or interface they were defined in, and are treated distinctly. The act of implementing the interface is completely distinct from any static members of that interface.
I suspect this is one of the reasons Kotlin's designers did not carry over the concept of static members and instead replaced it with companion objects. The concept of the class vs. the class object that has all the static members is confusing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论