Groovy命名参数的用法 [英] Groovy usage of named arguments
问题描述
我有类似这样的常规方法
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)
这给了我这个例外
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.
对于def foo(T t, p1, p2, ..., pn)
,所有命名参数都位于t中,但这也意味着您无法在通过名称访问pi的情况下进行方法调用.例子
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)
此代码将在运行时失败,因为foo方法需要两个参数,但是您提供的映射只是一个参数.
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?
推荐答案
使用命名参数调用函数,如下所示:
Calling the function with named arguments like this:
def testObj = createMyObj(id:10,instanceId:20,isValid:true)
表示您只向函数传递了一个参数[id:10,instanceId:20,isValid:true]
(即LinkedHashMap
).
means you're passing just one parameter,[id:10,instanceId:20,isValid:true]
which is a LinkedHashMap
, to the function.
很显然,createMyObj(id,instanceId,isValid)需要3个参数.因此,可以得到此异常是可以的:
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,..]]
对于后一种情况:
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")
在这种情况下,foo
获取
-
x
作为[x:1, y:2]
(是LinkedHashMap
) -
y
作为"newParameter"
x
as[x:1, y:2]
(which is aLinkedHashMap
)y
as"newParameter"
这篇关于Groovy命名参数的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!