Sobes.tech
Middle

Can you implement an equivalent of extension functions in Java?

sobes.tech AI

Answer from AI

Yes, directly — no, because Java does not support them at the syntax level like Kotlin. But you can imitate their behavior using static helper methods or the Decorator pattern.

1. Static helper methods:

Create a class with static methods that accept the object you want to "extend" as the first argument.

public class StringExtensions {
    // Method that mimics extension for String
    public static String capitalizeFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return input.substring(0, 1).toUpperCase() + input.substring(1);
    }
}

Usage:

String myString = "hello";
String capitalizedString = StringExtensions.capitalizeFirstLetter(myString);

2. Decorator pattern:

Create a wrapper class that implements the same interface as the original class (or extends it) and adds new functionality.

public interface MyInterface {
    void originalMethod();
}
public class MyClass implements MyInterface {
    @Override
    public void originalMethod() {
        System.out.println("Original method");
    }
}
// Decorator
public class MyInterfaceDecorator implements MyInterface {
    private MyInterface decorated;

    public MyInterfaceDecorator(MyInterface decorated) {
        this.decorated = decorated;
    }

    @Override
    public void originalMethod() {
        decorated.originalMethod();
    }

    // "Extended" functionality
    public void newMethod() {
        System.out.println("New extended method");
    }
}

Usage:

MyClass original = new MyClass();
MyInterfaceDecorator decorated = new MyInterfaceDecorator(original);
decorated.originalMethod();
decorated.newMethod();

Although these approaches are not as convenient as native extension functions in Kotlin, they allow adding functionality to existing classes without modifying their source code.