Junior — Middle
How are extensions, used in Kotlin, implemented in Java?
sobes.tech AI
Answer from AI
Java does not have direct support for extension functions like Kotlin. In Kotlin, extensions are implemented as static methods that appear as methods of the object.
To mimic extensions in Java, utility classes with static methods accepting an object as the first parameter are usually created.
Example:
public class StringExtensions {
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
}
// Usage
boolean result = StringExtensions.isNullOrEmpty(myString);
Thus, Kotlin extensions compile into static methods, which can be used in Java exactly like this.