groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <dinko.sr...@gmail.com>
Subject Re: Functional question : how to combine closures with same signature?
Date Wed, 19 Aug 2015 10:43:09 GMT
I'm not sure it can be done exactly as you described, but one can get
creative with bitwise operator overloading which might get close
enough:

    class LogicallyChallenged {
        static Closure and(Closure left, Closure right) {
            { a, b -> left(a, b) && right(a, b) }
        }

        static Closure or(Closure left, Closure right) {
            { a, b -> left(a, b) || right(a, b) }
        }
    }

    def gt = { a, b -> a > b },
        eq = { a, b -> a == b },
        lt = { a, b -> a < b }

    def equal = use (LogicallyChallenged) {
        (gt | eq) & (lt | eq)
    }

    assert equal(1, 1)
    assert equal('a', 'a')
    assert !equal(1, 2)
    assert !equal('a', 'b')

Cheers,
Dinko

On 19 August 2015 at 11:52, Mehdi Elaoufir <melaoufir@gmail.com> wrote:
> Hi Groovy people,
>
> I have business logic that is written in terms of small closure.
>
> I want to be able to combine as many closures as i want using logical
> operators &&, ||..
>
> All these closures have a similar functional signature :
> (DomainObject,User) -> boolean
>
> Say, for example these three closures :
>
> def isEnabled = {obj, user->user.enabled}
> def canAccessObject= {obj, user->obj.owner?.id==user.id}
> def isManager = {obj, user->user.hasRole('Manager')}
>
> I want to be able to have a closure with the same signature :
>
> def canProcessTransaction = isEnabled && canAccessObject || isManager
>
> assert canProcessTransaction(basket,userService.loggedInUser)
>
> Is there a Groovy way to do it?
>
>
> Best regards

Mime
View raw message