2009-10-17 46 views
7
def array = [1,2,3,4,5] 
println 3 in array 

打印true。我需要超载以支持任何对象的in如何在Groovy中重载in运算符?

例子:

class Whatever { 
    def addItem(item) { 
     // add the item 
    } 
} 

def w = new Whatever() 
w.addItem("one") 
w.addItem("two") 
println "two" in w 

我知道我可以让这个类使用公共的集合,但我想用in代替。

+0

你能举一个你想做的样品吗? – 2009-10-17 15:17:48

回答

8

我在Groovy邮件列表上询问。 Here's的线程。答案是isCase

class A 
{ 
    def isCase(o) { 
    return false; 
    } 
} 

a = new A() 
println 6 in a // returns false 
+0

甜。快速搜索后,看起来像这里记录:http://docs.codehaus.org/display/GROOVY/JN2535-Control#JN2535-Control-ConditionalStatements – 2009-10-19 19:53:10

+0

+1。我希望我可以为Guillaume Laforge投票支持这个+1,毕竟,他是在邮件列表中回答它的人之一;-) – Leonel 2009-11-05 15:53:02

1

我想知道这是否可能,会员运营商(中)没有列在Operator Overloading页面上。

+0

我也注意到了。 – Geo 2009-10-17 17:13:01

2

您可以使Whatever实现Collection或Collection子接口。 Groovy的iterator()implementationObject,它看起来像操作聚合对象的操作符,Groovy会尝试将该对象转换为集合,然后执行聚合函数。

或者,您可能能够有Whatever实施Iterable。我仍然试图为此找到一个参考,并写出一个概念验证来验证它。

Groovy documentation for the Iterator Pattern可能表明这会起作用。