Kotlin Inheritance - Extend JVM class and interface which have same method names

Viewed 407

I have a custom Exception class which looks like this:

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

As you all know, RuntimeException extends Throwable which has a method called getMessage()

Now the issue is, this interface GraphQLError (which is a library interface) also has a method called getMessage()

As a result, compiler is complaining with this:

constructor compiler error

OK so I implement the method:

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

Now I get this:

Override Error

What am I supposed to do here?

1 Answers

What I guessed in the comments was right, kotlin allows multiple inheritence. It was indeed because of the Throwable class.

You can use @JvmField annotation to instruct the compiler not to generate getters and setters for the field and then create the getter/setter yourself.

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.

Related