groovyclosuresnamed-parameters

How to mix named parameter and closure in Groovy


I want to write a method that takes named parameters only and a closure. See below.

def myMethod(Map args, Closure cl)

When I call the method, I can do something like this:

myMethod(param1: 'a', param2: 'b') {
  // do something in closure
}

// getting a MissingMethodException: No signature of method: myMethod() is applicable for argument types: (TestScript$_run_closure2$) values: ... 
myMethod {
  // do something in closure
}

Why do I get MissingMethodException if no argument is provided? I thought named parameter should allow it.


Solution

  • You should change your method definition to:

    def myMethod(Map args = [:], Closure cl) { ... }
    

    This will ensure a Closure only variant is available.