0

In my knowledge I don't think Java has Extension function such as kotlin . But i want to know is there any way have to Extended String class to create Extension function in java .

Kuvonchbek Yakubov
  • 558
  • 1
  • 6
  • 16
Faisal Mohammad
  • 427
  • 1
  • 9
  • 27
  • 3
    Sort answer: no. – akarnokd Jun 25 '22 at 18:29
  • Not short, but [already answered](https://stackoverflow.com/questions/28294509/accessing-kotlin-extension-functions-from-java) – hc_dev Jun 25 '22 at 18:31
  • 2
    `String` is a `final` class in Java that can not be extended. But you can define a utility-class with static methods there that operate on a String argument. Like in Apache's [StringUtils](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html). – hc_dev Jun 25 '22 at 18:33
  • Java does not support extension methods. Please take a look at [Java equivalent to C# extension methods](https://stackoverflow.com/questions/4359979/java-equivalent-to-c-sharp-extension-methods) for alternatives – Eskandar Abedini Jun 25 '22 at 19:03

1 Answers1

1

The Extension Manifold

Java itself does not support extension methods, so external libraries come to rescue. Manifold

With Manifold you can create an Extension Class:

@Extension
public class MyStringExtension {
  public static void echo(@This String thiz) {
    System.out.println(thiz);
  }
}

Here we’ve added a new echo() method to String, so we use it like this:

"Java".echo();

Reference: http://manifold.systems/docs.html#the-extension-manifold

Kuvonchbek Yakubov
  • 558
  • 1
  • 6
  • 16