让我们考虑下一个函数:
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)
}
..然后我又遇到了一个错误:
The current scope already contains a variable of the name text
问题是:我能否以某种方式从闭包访问其他参数,该闭包被指定为函数参数之一的默认值?
如果不是,那么为什么我不能使用与所描述的闭包内的函数参数之一相同的名称?
最佳答案
您可以使用默认的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
关于grails - 在 Groovy 中使用闭包指定默认参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11656815/