I think there should be some way (e.g. an annotati...
# language-proposals
s
I think there should be some way (e.g. an annotation) to ask the compiler to generate default implementations for Unit type functions of an interface. Take
android.text.TextWatcher
as an example. I am not interested in
beforeTextChanged()
and
onTextChanged()
, only
afterTextChanged()
. In a big action listener class (with many listener functions), this can be many functions that need to be implemented as
override fun foo() {}
. It would be convenient if I didn’t have to specify that the first two functions don’t do anything:
Copy code
object : TextWatcher {
            override fun beforeTextChanged(...) {}
            override fun onTextChanged(...) {}
            override fun afterTextChanged(...) {
                ...
            }
        }
p
IMO this is a library/API problem that should be solved at that layer (e.g. Swing’s ‘XAdapter’, abstract classes with empty bodies for each interface method) or even better, some more granular approach to add lambdas. I don’t think this is a language feature that’s worth adding
☝️ 5
j
You can do that using interface delegation:
Copy code
object DoNothingTextWatcher : TextWatcher {
    override fun beforeTextChanged() = Unit
    override fun onTextChanged() = Unit
    override fun afterTextChanged() = Unit
}

fun main() {
    val myWatcher = object : TextWatcher by DoNothingTextWatcher {
        override fun afterTextChanged() {
            println("hello")
        }
    }
    myWatcher.beforeTextChanged()
    myWatcher.onTextChanged()
    myWatcher.afterTextChanged()
}
s
@jbnizet So for every single interface I want to implement partially I have to write another class? In Android, the APK size can really start to grow.
j
You don’t have to. But you can.
s
…I do if i don’t want to implement every function.
j
You can also write a base class and extend it. if you prefer that solution. That’s what Swing’s Adapter classes are designed to do. I’m just suggesting alternatives to your language proposal to help, because there’s very little chance this proposal is implemented: The proper solution, as it has been said before, would be for Android to use functional interfaces instead of classes with multiple methods.
p
how would a language feature that autogenerates these have a different impact on the APK size than writing them manually?
s
@Paul Griffith because if the compiler writes it inline then it won’t increase the APK size as much as adding a class.