How to overload the in operator in Groovy?

def array = [1,2,3,4,5] println 3 in array 

prints true . What do I need to overload to support in for any object?

Example:

 class Whatever { def addItem(item) { // add the item } } def w = new Whatever() w.addItem("one") w.addItem("two") println "two" in w 

I know that I could make a collection, that this class uses public, but I would like to use in .

+7
operator-overloading language-features groovy
source share
3 answers

I asked on the Groovy mailing list. Here is the flow. Answer: isCase

 class A { def isCase(o) { return false; } } a = new A() println 6 in a // returns false 
+8
source share

You can do Whatever implement Collection or a collection sub-industry. Groovy has an iterator() implementation for Object , and it looks like operators working on aggregate objects, Groovy will try to convert the object to a collection, and then perform the aggregate function.

Alternatively, you can have Whatever implement Iterable . I am still trying to find a link for this and write a proof of concept to test it.

The Groovy documentation for the iterator template may indicate that this will work.

+2
source share

I wonder if this is possible, the membership operator (in) is not listed on the Operator Overload page.

+1
source share

All Articles