How to access an enum member of a Java interface using Kotlin?

Tags: , ,



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?

Answer

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.



Source: stackoverflow