【问题标题】:In Kotlin, how can I work around the inherited declarations clash when an enum class implements an interface?在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?
【发布时间】:2017-11-17 02:24:23
【问题描述】:

我定义了一个实现 Neo4j 的RelationshipType 的枚举类:

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

我收到以下错误:

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

我了解Enum 类中的name() 方法和RelationshipType 接口中的name() 方法具有相同的签名。不过这在 Java 中不是问题,那么为什么在 Kotlin 中会出现错误,我该如何解决呢?

【问题讨论】:

    标签: enums interface kotlin


    【解决方案1】:

    它是一个 bug-KT-14115 即使你让enum 类实现了包含name() 函数的接口 被拒绝。

    interface Name {
        fun name(): String;
    }
    
    
    enum class Color : Name;
           //   ^--- the same error reported
    

    但是您可以使用sealed 类来模拟enum 类,例如:

    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】:

      上面的示例使用具有属性name 而不是函数name() 的接口。

      interface Name {
          val name: String;
      }
      
      enum class Color : Name {
          Blue
      }
      

      【讨论】:

      • 虽然我理解反对意见,因为它对第三方接口(如 RelationshipType)没有帮助,但它是一种在接口中使用枚举名称的方法。
      猜你喜欢
      • 2018-02-09
      • 2018-05-30
      • 1970-01-01
      • 2014-07-11
      • 2019-11-16
      • 2019-03-04
      • 2020-10-17
      • 2019-01-05
      • 1970-01-01
      相关资源
      最近更新 更多