我需要一個Groovy 1.8 DSL功能的幫助。Groovy 1.8 a b c風格
考慮this測試用例:
/**
* For odd number of elements, treat the last element as a call to a getter
*
* case a b c
* equivalent a(b).getC()
*/
void testTrailingElementAsGetter() {
def drank = false
def more = 'more'
def drink = { String s -> [milk: { drank = true }()] }
def d = drink more milk
assert drank
}
如果我改變[milk: { drank = true }()]
到[foo: { drank = true }()]
,測試用例依然通過。這可能是新實現中的一個錯誤,或者我錯過了Groovy語法中的某些東西?
編輯 - 已解決:@han和@Gareth Davis都發布了正確的線索。這裏有一些更多的細節來了解一下測試:
groovy:000> more = 'more'
===> more
groovy:000> drank = false
===> false
groovy:000> drink = { String s -> [milk: { drank = true }()] }
===> [email protected]
[A] groovy:000> drink more
===> {milk=true}
[B] groovy:000> drank
===> true
groovy:000> drink more milk
===> true
groovy:000> drink more water
===> null
線爲@han指出[A]
返回地圖。由於在創建後立即執行了封閉(如@Gareth Davis指出的),因此在行[B]
,drank
已經是true
,類似於JavaScript module pattern。我不認爲這個「測試」是展示這種功能的最佳方式 - drank
的副作用是不正確的。