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

无人久伴 提交于 2019-12-18 21:18:10

问题


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?


回答1:


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);



回答2:


The example above is working with an interface having a property name instead of a function name().

interface Name {
    val name: String;
}

enum class Color : Name;


来源:https://stackoverflow.com/questions/44553148/in-kotlin-how-can-i-work-around-the-inherited-declarations-clash-when-an-enum-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!