Feature Request: Delegate by nothing

#1

It’s quite common to create a concrete class which implements an interface for just a single method or two even though the interface has many more methods. This is especially common when creating fakes in tests so we end up overriding every single one only to provide an empty body.

As an example, when we want to handle mouse clicks, we implement MouseListener which has several other methods that we don’t care about. Having concrete do-nothing stubs like MouseAdapter doesn’t always work due to multiple-inheritance limitations.

Here is what the mouse click example could look like in a future version of Kotlin:

class MouseHandler : MouseListener by nothing {
    override fun mouseClicked(event: MouseEvent) {
        // Do something for mouseClicked and do nothing for all the other methods
    }
}

Methods with return type Unit would be empty and methods with all other return types would throw an exception to indicate that it’s not implemented.

Would it be possible to have a special delegate which automatically provides do-nothing stubs for all the methods?

3 Likes