Reputation: 1459
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?
Upvotes: 7
Views: 13251
Reputation: 3689
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"
Upvotes: 12