Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, how can I work around the inherited declarations clash when an enum class implements an interface?

I define an enum class that implements Neo4j's RelationshipType:

enum class MyRelationshipType : RelationshipType {
    // ...
}

I get the following error:

Inherited platform declarations clash: The following declarations have the same JVM signature (name()Ljava/lang/String;): fun <get-name>(): String fun name(): String

I understand that both the name() method from the Enum class and the name() method from the RelationshipType interface have the same signature. This is not a problem in Java though, so why is it an error in Kotlin, and how can I work around it?

like image 589
Laurent Pireyn Avatar asked Jun 14 '17 19:06

Laurent Pireyn


People also ask

Can enum implement an interface in Kotlin?

Just like in Java, a kotlin enum can implement an interface. However, each instance of the enum has to implement the interface, which is why we now have a class body after each declaration of the enum.

Can an enum class be inherited by another class?

Inheriting an enum Class from Another Class It is because all enums in Java are inherited from java. lang. Enum . And extending multiple classes (multiple inheritance) is not allowed in Java.

Can enum class have methods Kotlin?

Since Kotlin enums are classes, they can have their own properties, methods, and implement interfaces.


1 Answers

it is a kotlin bug-KT-14115 even if you makes the enum class implements the interface which contains a name() function is denied.

interface Name {
    fun name(): String;
}


enum class Color : Name;
       //   ^--- the same error reported

BUT you can simulate a enum class by using a sealed class, for example:

interface Name {
    fun name(): String;
}


sealed class Color(val ordinal: Int) : Name {
    fun ordinal()=ordinal;
    override fun name(): String {
        return this.javaClass.simpleName;
    }
    //todo: simulate other methods ...
};

object RED : Color(0);
object GREEN : Color(1);
object BLUE : Color(2);
like image 175
holi-java Avatar answered Oct 11 '22 17:10

holi-java