groovyobjectlanguage-featurescallable

Is there a way to have callable objects in Groovy?


If for example I have a class named A. Can I make an object be callable, just like Python does? For example :


def myObject = new A()
myObject()

and that would call some object method. Can it be done?


Solution

  • In Groovy only closures are callable by default. E.g. Classes are not callable out of the box. If necessary you can dynamically add a call method to a type's ExpandoMetaClass to make all instances of that type callable.

    Hint: you can try out all code sample using the GroovyConsole

    Closures are callable by default in Groovy:

    // A closure
    def doSomething = { println 'do something'}
    doSomething()
        
    // A closure with arguments
    def sum = {x, y -> x + y}
    sum(5,3)
    sum.call(5,3)
        
    // Currying
    def sum5 = sum.curry(5)
    sum5(3)
    

    To make all instances of a specific type callable you can dynamically add a call method to its meta class:

    MyObject.metaClass.call = { println 'I was called' }
    def myObject = new MyObject()
    myObject()
    

    If you rather only make a specific instance callable you can dynamically add a call method to its meta class:

    def myObject = new MyObject()
    myObject.metaClass.call = { println 'Called up on' }
    myObject()