Home > Net >  Kotlin implicit override using delegation
Kotlin implicit override using delegation

Time:06-18

I have the following base class and interface

open class Base {
    open fun foo() { println("Base.foo") }
}

fun interface Delegate {
    fun foo(): Unit
}

Now I want to override the foo method of a subclass Composed of Base using delegation, like this:

class Composed(delegate: Delegate) : Base(), Delegate by delegate

This works as I intend. Instances of Composed use the foo method of delegate, instead of the one from Base. But, I get a warning from IntelliJ:

Delegated member 'fun foo(): Unit' hides supertype override: public open fun foo(): Unit defined in Base. Please specify proper override explicitly.

Why do I get this error? What is "bad" about implicitly overriding the foo method? Are there any drawbacks I don't see? Specifying the override explicitly seems like a lot of unnecessary code, especially if I do this for multiple methods and multiple subclasses.

CodePudding user response:

I think there's a warning for at least two reasons:

  1. The behavior is ambiguous about which foo() implementation is used. There's no intuitive expectation about which foo() should win, since the superclass and the delegate are declared on the same line. I've been using Kotlin for a few years, and I couldn't have told you which behavior to expect without testing it, because this is kind of an unusual setup.

  2. You will get possibly unexpected behavior if any of the functions in the Base superclass call foo(), because they will be calling the delegate's foo() instead of their own. It might be OK in this case, but in most cases, when you override a function, you want to call super in case there are necessary side-effects. That's not possible with the delegate.

  • Related