How to mix named parameter and closure in Groovy

37 Views Asked by At

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.

1

There are 1 best solutions below

0
Paul King On BEST ANSWER

You should change your method definition to:

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

This will ensure a Closure only variant is available.