I have a groovy method like this
def createMyObj(id,instanceId,isValid) {
def myObj = new SomeObj()
myObj.setId(id)
myObj.setInstanceId(instanceId)
myObj.isValid(isValid)
myObj
}
I have tests around this when I explicitly do this in the test it works perfectly fine.
def testObj = createMyObj(10,20,true)
when I tried to use named arguments like this.
def testObj = createMyObj(id:10,instanceId:20,isValid:true)
it's giving me this exception
No signature of method:createMyObj is applicable for argument types: (java.util.LinkedHashMap) values [[id:10, instanceId:20,..]]
I went to this page to understand the concept a little further and I saw this piece of snippet.
In case of def foo(T t, p1, p2, ..., pn)
all named arguments will be in t, but that also means that you can not make a method call where you access pi by name. Example
def foo(x,y){}
foo(x:1,y:2)
This code will fail at runtime, because the method foo expects two arguments, but the map you gave is only one argument.
I am not sure if it's the cause of the error I am facing. If it expects two arguments like it says what is the argument that i am missing or how do I pass the second argument?
Groovy collects all named parameters and puts them in a Map. The Map is passed on to the method as the first argument.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
Java does not support Objective-C-like named parameters for constructors or method arguments.
In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.
Calling the function with named arguments like this:
def testObj = createMyObj(id:10,instanceId:20,isValid:true)
means you're passing just one parameter,[id:10,instanceId:20,isValid:true]
which is a LinkedHashMap
, to the function.
Obviously, createMyObj(id, instanceId, isValid) requires 3 parameters. So it's ok that you get this exception:
No signature of method:createMyObj is applicable for argument types: (java.util.LinkedHashMap) values [[id:10, instanceId:20,..]]
For the latter case:
def foo(x,y){}
foo(x:1,y:2)
In order to pass a second parameter, you just need to add one more parameter on invoke, like this:
def foo(x,y){}
foo(x:1,y:2,"newParameter")
In this case foo
gets
x
as [x:1, y:2]
(which is a LinkedHashMap
)y
as "newParameter"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With