Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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 I could make the collection this class uses public, but I'd like to use in instead.

like image 739
Geo Avatar asked Oct 17 '09 14:10

Geo


2 Answers

I asked on the Groovy mailing list. Here's the thread. The answer is isCase

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

a = new A()
println 6 in a // returns false
like image 110
Geo Avatar answered Sep 28 '22 07:09

Geo


You could make Whatever implement Collection or a Collection subinterface. Groovy has an iterator() implementation for Object, and it looks like for operators that work on aggregate objects, Groovy will attempt to convert the Object to a Collection and then perform the aggregate function.

Alternatively, you might be able to have Whatever implement Iterable. I'm still trying to find a reference for this and write a proof of concept to verify it.

The Groovy documentation for the Iterator Pattern might indicate that this will work.

like image 26
Rob Hruska Avatar answered Sep 28 '22 05:09

Rob Hruska