OlliP
OlliP

Reputation: 1585

Extension Methods in Java possible without breaking Binary Backwards Compatibility?

Several languages have externsion methods like C#, Ruby, Smalltalk, Kotlin, Scala. The idea is that you can add methods to a class that is closed for extension like system classes such as String, Integer or final classes such as ArrayList.

So instead of having all those Util-Classes you just add the respective extension method. So instead of StringUtils.split(...) you would call "foo".split().

Java does not have extension methods. My question is whether extension methods could be added to Java without breaking binary backwards compatibility as for exanple with Java8 lambdas or other features in the past. The question is only about whether it can be done without braking backwards compatibility or not.

In C# and Kotlin extension methods are implemented as static methods. So, in the same way for Java there would be some additional syntax for StringUtils.split(...), which would tell the Java compiler that "foo".split() at compile time has to be replaced with StringUtils.split(...). At least, I think this is what happens in C# and Kotlin.

Again, my question is only about whether extension methods in Java can be done without braking backwards compatibility or not. Just that.

Upvotes: 0

Views: 1130

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81989

I don't know the ultimate answer to this but here's how Kotlin does it, which would probably be possible for Java as well.

Let's consider a simple extension on String:

fun String.lengthSquare() = length * length

The Kotlin compiler generates bytecode similar to the following (shown as corresponding Java code):

public static final int lengthSquare(@NotNull String $this$lengthSquare) {
   Intrinsics.checkParameterIsNotNull($this$lengthSquare, "$this$lengthSquare");
   return $this$lengthSquare.length() * $this$lengthSquare.length();
}

So basically it just creates a static method that takes in a String, just as we know it from utility methods. I believe the Java compiler could do something similar. All call sites of those extension functions, of course, will use that static method in the JVM byte code.

More Information on Kotlin Extensions

Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.

Upvotes: 1

Related Questions