Is telling the user that the Closure cannot be empty the only application for this ? If yes, given that a user can easily pass a non-empty but non-meaningful closure anyway I would question whether it is worth the effort.

Cheers,
mg

PS: Also wondering whether we could achieve the same thing through the Closure return type, e.g.:

@Test @Ignore void closureFooTest() {
 println closureFoo {}
 println closureFoo{ "abc" } }

def closureFoo(Closure<String> cls) {
 return "the string is: ${cls()}" }

Should imho fail to compile, since an empty Closure should have return type void. Currently it does compile and run though (under 2.5.x) , even with @CompileStatic, since the empty closure implicitely returns null (imho one of the few bad design decisions in Groovy (whether in closures or somewhere else)), but at least IntelliJ marks it as invalid...



On 17/02/2021 19:51, Daniel Sun wrote:
Groovy does not support checking empty closure at runtime AFAIK, but we could 
check and set some property to closure while compiling, then get the property 
at runtime. It will be an new improvement, not sure if others like it or not.

Cheers,
Daniel Sun

On 2021/02/17 15:06:47, OCsite <[email protected]> wrote:
Hi there,

is it possible to reliably recognise an empty closure, i.e., „{}“, 
programmatically?

def foo(Closure bar) {
   if (?bar-is-empty?) throw new Exception('The closure cannot be empty!')
   else bar()
}
foo { println "ok" } // OK
foo { 1 } // OK
foo { } // throws

Thanks!
OC

Reply via email to