https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
s

Sam Stone

03/09/2023, 12:05 AM
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

Paul Griffith

03/09/2023, 12:20 AM
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

jbnizet

03/09/2023, 4:44 PM
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

Sam Stone

03/09/2023, 7:16 PM
@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

jbnizet

03/09/2023, 8:22 PM
You don’t have to. But you can.
s

Sam Stone

03/09/2023, 8:26 PM
…I do if i don’t want to implement every function.
j

jbnizet

03/09/2023, 8:30 PM
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

Paul Griffith

03/09/2023, 9:07 PM
how would a language feature that autogenerates these have a different impact on the APK size than writing them manually?
s

Sam Stone

03/09/2023, 10:41 PM
@Paul Griffith because if the compiler writes it inline then it won’t increase the APK size as much as adding a class.
10 Views