Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Groovy in operator work?

The Groovy "in" operator seems to mean different things in different cases. Sometimes x in y means y.contains(x) and sometimes it seems to call y.isCase(x).

How does Groovy know which one to call? Is there a particular class or set of classes that Groovy knows about which use the .contains method? Or is the behavior triggered by the existence of a method on one of the objects? Are there any cases where the in operator gets changed into something else entirely?

like image 727
ataylor Avatar asked Jan 14 '10 23:01

ataylor


People also ask

What does operator do in Groovy?

Groovy Programming Fundamentals for Java Developers An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

What does == mean in Groovy?

Thankfully, a different portion of the Groovy Language Documentation saves the day: Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

Does Groovy have ternary operator?

Another one of the great operators that more and more languages support is their ternary operator. The ternary is a conditional operator and often referred to as an inline if statement. Before we look at how to use it lets take a look at a common problem it helps us solve.


1 Answers

I did some experimentation and it looks like the in operator is based on the isCase method only as demonstrated by the following code

class MyList extends ArrayList {
    boolean isCase(Object val) {
        return val == 66
    }
}

def myList = new MyList()
myList << 55
55 in myList // Returns false but myList.contains(55) returns true     
66 in myList // Returns true but myList.contains(66) returns false

For the JDK collection classes I guess it just seems like the in operator is based on contains() because isCase() calls contains() for those classes.

like image 109
Dónal Avatar answered Oct 16 '22 18:10

Dónal