Search code examples
javagrailsgroovyclosures

Create method like createCriteria().list(){} in Groovy


I want to create a method that has multi params when I call that method need to create a closure to call that method.

For example in Grails we have:

 User.createCriteria().list(){}

I want to create a method like list.


Solution

  • You just have to declare a method that takes a closure as parameter. If the last parameter in the list is a closure, then it can be invoked in that fashion:

    def doSomething(int arg1, int arg2, Closure arg3) {
        arg3(arg1, arg2)
    }
    

    And you can invoke either as:

    doSomething(3, 5) {a,b -> a + b}
    

    Or as:

    doSomething(3, 5, {a,b -> a + b})
    

    The method can also have no other argument but the closure:

    def doSomething(Closure arg3) {
        arg3()
    }
    
    print doSomething {println "closure invoked"}
    print doSomething() {println "closure invoked"}
    

    More information can be found on the closure documentation page.