Archer
Archer

Reputation: 5147

Method aliasing in class with Groovy

I'm going to internationalize groovy API abit.

For final class (e.g. String)

String.metaClass.вСтроку = {-> this.toString() }

However, this will create additional closure. Isn't there any way to just alias method with another method?

Something like this:

String.metaClass.вСтроку = String.metaClass.&toString

Upvotes: 0

Views: 283

Answers (1)

Seagull
Seagull

Reputation: 13859

You could use @Category transform like this

@Category(String) class StringInternationalization {
    String вСтроку() {
        this.toString()
    }

    int длина() {
        this.length()
    }
}

class ApplyMixin {
    static {
        String.mixin(StringInternationalization)
        final helloString = "Привет мир!"
        println helloString.вСтроку()
        assert helloString.длина() == helloString.length()
    }
}

new Main()

This will create 1 Category class for each localised class and one class to apply all mixin transformations(to register all methods.) Also should be faster, then individual closures.

More reading here: http://groovy.codehaus.org/Category+and+Mixin+transformations

Upvotes: 3

Related Questions