Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Groovy have extension methods like in C#?

Can I add to a method to a final class somehow like in C#?

So I could do something like:

"Some text".myOwnFunction();

Instead of:

MyStaticClass.myOwnFunction("Some text");
like image 539
Mustafa Avatar asked Apr 30 '16 12:04

Mustafa


1 Answers

You can either add it to all future string instances via the metaClass

    String.metaClass.myOwnFunction = {-> delegate.length() }
    assert "Tim".myOwnFunction() == 3

Or you can add it to a single instance

    String a = "Tim"
    a.metaClass.myOwnFunction = {-> delegate.length() }
    assert a.myOwnFunction() == 3

Or you can add these methods when a jar is in the classpath at startup with extension modules

like image 111
tim_yates Avatar answered Nov 09 '22 15:11

tim_yates