2012-07-25 39 views
2
指定默认参数值

让我们考虑下一个功能:使用闭包用于在Groovy

def generateUniqueIdent(String text, uniqueSuffix = {uid -> String.valueOf(uid)}) { 
    doSomething(text) + uniqueSuffix() 
} 

现在,当我试了下修改:

def generateUniqueIdent(String text, uniqueSuffix = { hash(text) }) { 
    doSomething(text) + uniqueSuffix() 
}   

..我得到了一个错误:

| Error Fatal error during compilation org.apache.tools.ant.BuildException: BUG! exception in phase 'class generation' in source unit 'some path here' tried to get a variable with the name text as stack variable, but a variable with this name was not created (Use --stacktrace to see the full trace)

与此同时,如果我尝试使用名称text作为封闭的参数:

def generateUniqueIdent(String text, uniqueSuffix = {text -> hash(text) }) { 
    doSomething(text) + uniqueSuffix(text) 
}  

..then我得到另一个错误:

The current scope already contains a variable of the name text

的问题是:我可以以某种方式得到封闭,其被指定为默认值的函数参数的一个访问其他参数?

如果否,那么为什么我不能使用与描述的闭包内部的函数参数之一相同的名称?

回答

2

你可以使用默认的it参数:

def generateUniqueIdent(String text, uniqueSuffix = { hash(it) }) { 
    doSomething(text) + uniqueSuffix(text) 
} 

working example

或为封闭参数,而不是text使用不同的名称:

def generateUniqueIdent(String text, uniqueSuffix = { x -> hash(x) }) { 
    doSomething(text) + uniqueSuffix(text) 
} 

example

不幸的是,在这种情况下访问从关闭is working的前一个参数对我来说,所以我不知道什么原始问题是:S

+0

感谢您验证,它的工作原理。所以,无论是使用groovy/grails还是使用IDE插件都会导致问题。 – Roman 2012-07-25 20:00:34

+0

@罗曼做第一或第二个解决方案的工作?如果没有,错误是什么样的? – epidemian 2012-07-25 22:09:53

+1

@Roman如果我为'text'参数设置了一个默认参数,我可以得到'BUG!'异常。我发布了一个bug [这里是Groovy JIRA](https://jira.codehaus.org/browse/GROOVY-5632) – 2012-07-26 08:01:34