在groovy中为数组重载+运算符 [英] Overloading + operator for arrays in groovy

查看:283
本文介绍了在groovy中为数组重载+运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个时髦的新手。也许这是小菜一碟,但我想重载数组/列表的+运算符来编写代码,如

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

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


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

一个更加本地化的选择是使用一个类别: / p>

  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]
}

然而,我可能会创建一个通用的zipWith方法编程),允许人们轻松指定不同的行为......

  Collection.metaClass.zipWith = {Collection b,Closure 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}


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 

解决方案

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}

这篇关于在groovy中为数组重载+运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆