Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like Extension Functions for Java or other popular languages?

Tags:

java

kotlin

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.

  1. Were there any concept of this feature in Java or other popularly used programming languages?

  2. If the previous answer is no, are there any kind of workaround to implement extensions in Java or other languages?

like image 924
Abhiroop Nandi Ray Avatar asked Mar 08 '18 10:03

Abhiroop Nandi Ray


2 Answers

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 ...

like image 114
Tomasz Bawor Avatar answered Oct 20 '22 10:10

Tomasz Bawor


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.

like image 31
Maroš Šeleng Avatar answered Oct 20 '22 11:10

Maroš Šeleng