Overloading + operator for arrays in groovy

前端 未结 1 575
既然无缘
既然无缘 2021-01-27 16:50

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]

asse         


        
相关标签:
1条回答
  • 2021-01-27 17:22

    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}
    
    0 讨论(0)
提交回复
热议问题