grails - 在 Groovy 中使用闭包指定默认参数值

标签 grails groovy parameters closures

让我们考虑下一个函数:

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/

相关文章:

java - 我如何检查字符串是否是 Groovy 中的 IP?

jenkins - 如何访问groovy类文件中的全局变量?

c++ - 有什么方法可以将右值/临时对象传递给需要非成本引用的函数?

java - 将数组名称作为类方法中的参数传递

javascript - svg 标签的复杂参数(css 的模拟 calc())

spring - 提前释放 Grails 数据库连接

grails - Grails GORM一对多问题

grails - 仅使用脚手架,Grails错误无法创建Bean

mysql - Grails + MySQL : No suitable driver found

java - 加载和分析海量数据