超载+ groovy 中数组的运算符

发布于 2024-10-07 10:49:41 字数 132 浏览 0 评论 0原文

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

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

assert [3,3,3] == 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 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡忘如思 2024-10-14 10:49:41

我不建议在全球范围内覆盖既定的行为。但是,如果您坚持,这将按照您的要求进行:

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

一种更本地化的替代方案是使用类别:

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

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}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文