【问题标题】:Kotlin Inheritance - Extend JVM class and interface which have same method namesKotlin Inheritance - 扩展具有相同方法名称的 JVM 类和接口
【发布时间】:2020-08-29 05:04:35
【问题描述】:

我有一个自定义的 Exception 类,如下所示:

class GenericException(message: String?, errorCode: Int) : RuntimeException(message), GraphQLError {
.....
}

众所周知,RuntimeException extends Throwable 有一个名为 getMessage() 的方法

现在的问题是,这个接口GraphQLError(这是一个库接口)有一个名为getMessage()的方法

因此,编译器抱怨:

好的,所以我实现了这个方法:

override fun getMessage(): String {
    TODO("Not yet implemented")
}

现在我明白了:

我应该在这里做什么?

【问题讨论】:

标签: kotlin graphql graphql-java


【解决方案1】:

我在 cmets 中的猜测是对的,kotlin 允许多重继承。确实是因为 Throwable 类。

您可以使用@JvmField注解来指示编译器不要为字段生成getter和setter,然后自己创建getter/setter。

interface HasMessage {
    fun getMessage(): String
}

class GenericException(
    @JvmField override val message: String?,  // var is also possible
    val errorCode: Int                        // I made it a property, might not be as well
) : RuntimeException(message), HasMessage {
    override fun getMessage(): String {
        // return of the super's getter, probably no use because you have field as property in this class
        val superGetMessage = super<RuntimeException>.message
        TODO("Not yet implemented")
    }
}

Play with the code yourself.

【讨论】:

  • 非常感谢!那行得通!今天学习了一个新概念。
  • 您能否在Kotlin issue 中添加一条提及这项工作的评论?
  • 现在1.6不支持
猜你喜欢
  • 1970-01-01
  • 2011-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 2018-05-26
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多