Search code examples
javamethodsextension-methods

How to create extention Function in java just like kotlin


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 .


Solution

  • 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