2009-10-17 45 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可能表明這會起作用。