In Kotlin, we have a beautiful feature like Extension. Where even a newer custom method can be added to the super class whose object has been instantiated. That method can be accessed by the object created in the code.
My question is basically forked into two.
Were there any concept of this feature in Java or other popularly used programming languages?
If the previous answer is no, are there any kind of workaround to implement extensions in Java or other languages?
Currently there seems to be no feature in java to provide such functionality, however Lombok provides us with alternative by using @ExtensionMethod
annotation to extend api without extending classes. There is example provided on their web page:
https://projectlombok.org/features/experimental/ExtensionMethod
As you can see this feature is experimental though ...
Swift has very similar extensions functionality. You can find more on them here.
If you look, what extension functions in Kotlin compile to, you will see, that they are good old Java static methods with receiver as the first parameter, so I guess the best way how to do this in java is using static methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With