How do I overload the in operator in Groovy?

Tag: groovy , operator-overloading , language-features Author: bushideo Date: 2009-10-01
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?


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

def w = new Whatever()
println "two" in w

I know I could make the collection this class uses public, but I'd like to use in instead.

Can you give a sample of what you'd like to do?

Best Answer

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


Sweet. After a quick search, looks like that's documented here:…
+1. I wish I could vote Guillaume Laforge for this +1, after all, he was the one to answer it on the mailing list ;-)

Other Answer1

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.

Other Answer2

I wonder if this is possible, the Membership Operator (in) isn't listed on the Operator Overloading page.


I noticed that too.

Other Answer3

Have you tried creating an "in" method?


in is a language keyword. I get a compilation error.