2012-07-25 40 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