如何使用Kotlin访问Java接口的枚举成员?

huangapple go评论87阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月12日 22:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63379212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定