Friday, March 16, 2007

Return Statement Inside The Closures In The Functions

Regarding Groovy Categories:
Return statements inside the functions don't return anything if used in the "use" closures:




class TokenCategory3 {
static String g(String self) {
return 'hello'
}
}
String f() {
use(TokenCategory3) {
assert 'a'.g() == 'hello'
return 'a'.g()
}
}
use(TokenCategory3) {
assert 'a'.g() == 'hello'
}
assert f() == null


Note that the last line returns null, although there is a return statement in f().
To make f() return some value, the return statement should be outside the "use" closure:


String h() {
String result
use(TokenCategory3) {
result = 'a'.g()
}
return result
}
assert h() == 'hello'

No comments: