Overloading + operator for arrays in groovy

2019-03-03 16:32发布

问题:

I am a groovy newbie. Maybe this is a piece of cake, but I want to overload the + operator for arrays/lists to code like this

def a= [1,1,1]
def b= [2,2,2]

assert [3,3,3] == a + b 

回答1:

I wouldn't recommend globally overriding well-established behaviors. But, if you insist, this will do as you ask:

ArrayList.metaClass.plus << {Collection b -> 
    [delegate, b].transpose().collect{x, y -> x+y}
}

A more localized alternative would be to use a category:

class PlusCategory{
    public static Collection plus(Collection a, Collection b){
        [a, b].transpose().collect{x, y -> x+y}
    }
}
use (PlusCategory){
    assert [3, 3, 3] == [1, 1, 1] + [2, 2, 2]
}

However, I would probably create a generic zipWith method (as in functional programming), allowing one to easily specify different behaviors...

Collection.metaClass.zipWith = {Collection b, Closure c -> 
    [delegate, b].transpose().collect(c)
}
assert [3, 3, 3] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a+b}
assert [2, 2, 2] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a*b}