groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Felix Dorner <felix.dor...@gmail.com>
Subject Re: Aw: Do closures always return a value?
Date Fri, 04 Dec 2015 11:11:41 GMT
>> Is it possible to declare a closure to have type 'void' somehow?
>
> currently not

Ok. What happens if the last statement in a closure is a call to a void 
method?

>> I would like to exploit this somehow like this:
>>
>> def someMethod(Closure closure){
>>
>>       if (closure has no return value, or is somehow defined to be 'void'){
>>         closure()
>>       } else {
>>               if (closure()){
>>                     doSomething()
>>               } else {
>>                     doSomethingElse()
>>               }
>>       }
>> }
>
> normally it makes no sense to have a logic like this.

I wouldn't ask for it if it wouldn't make at least a bit of sense to me, 
but I'm maybe overwhelmed and want to define a WorldDomination API in a 
single method definition. So here you go:

interface TreeIterator extends Iterator {
     void prune()
}

Instances of this interface are used to walk over a tree structure and 
can be used like this:

while (iterator.hasNext()){
     Object next = it.next()
     doSomethingWith(next)
     if (!childrenAreInteresting(next)){
	it.prune() // this skips the subtree of the current element
     }
}

In groovy it would work somehow like this, with a closure:

iterator.each {
     doSomethingWith(it)
     childrenAreInteresting(next) // the 'each' implementation takes the 
closure result and calls prune() if the result is false
}

But sometimes I want to walk the whole tree and forget about having to 
return a value:

iterator.each {
     doSomethingWith(it)
     true
}

I would like to get rid of the forced 'true' as the last statement.

Felix

Mime
View raw message