Sobes.tech
Junior — Middle

How can you create an extension function in Java?

sobes.tech AI

Answer from AI

Java does not have built-in support for extension functions like Kotlin does. However, a similar effect can be achieved using static methods in utility classes that accept an object of the desired type as a parameter.

Example:

public class StringUtils {
    public static boolean isNullOrEmpty(String s) {
        return s == null || s.isEmpty();
    }
}

// Usage:
boolean empty = StringUtils.isNullOrEmpty(myString);

Thus, although Java does not have the syntax for extension functions, you can create static methods that operate on objects of a specific type, mimicking the extension of functionality.