Overloading + operator for arrays in groovy

淺唱寂寞╮ 提交于 2019-12-20 05:47:16

问题


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}


来源:https://stackoverflow.com/questions/4443557/overloading-operator-for-arrays-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!