How does the Groovy in operator work? - groovy

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?

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.

It's actually all based on isCase. Groovy adds an isCase method to Collections that is based on the contains method. Any class with isCase can be used with in.

in is the "Membership operator".
From the documentation for Groovy 3 (emphasis mine):
8.6. Membership operator
The membership operator (in) is equivalent to calling the isCase
method. In the context of a List, it is equivalent to calling
contains, like in the following example:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list) # (1)
(1) equivalent to calling list.contains('Emmy') or list.isCase('Emmy')
So, Groovy always calls isCase, which in case of a List maps to contains.

Related

Groovy compareTo for CustomClass and numbers/strings

I am building DSL and try to define a custom class CustomClass that you can use in expressions like
def result = customInstance >= 100 ? 'a' : 'b'
if (customInstance == 'hello') {...}
Groovy doesn't call == when your class defines equals and implements Comparable (defines compareTo) at the same time.
Instead Groovy calls compareToWithEqualityCheck which has a branching logic. And unless your custom DSL class is assignable from String or Number your custom compareTo won't be called for the example above.
You can't extend CustomClass with String.
I feel like I am missing something. Hope you can help me figure out how to implement a simple case like I showed above.
Here is a short answer first: You could extend GString for the CustomClass. Then its compareTo method will be called in both cases - when you check for equality and when you actually compare.
Edit: Considering the following cases, it will work for 1 and 2, but not for 3.
customInstance >= 100 // case 1
customInstance == 'hallo' // case 2
customInstance == 10 // case 3
Now I will explain what I understand from the implementation in Groovy's ScriptBytecodeAdapter and DefaultTypeTransformation.
For the == operator, in case Comparable is implemented (and there is no simple identity), it tries to use the interface method compareTo, hence the same logic that is used for other comparison operators. Only if Comparable is not implemented it tries to determine equality based on some smart type adjustments and as an ultima ratio falls back to calling the equals method. This happens in DefaultTypeTransformation.compareEqual#L603-L608
For all other comparison operators such as >=, Groovy delegates to the compareToWithEqualityCheck method. Now this method is called with the equalityCheckOnly flag set to false, while it is set to true for the first case when it the invocation originates from the == operator. Again there is some Groovy smartness happening based on the type of the left side if it is Number, Character, or String. If none applies it ends up calling the compareTo method in DefaultTypeTransformation.compareToWithEqualityCheck#L584-L586.
Now, this happens only if
!equalityCheckOnly || left.getClass().isAssignableFrom(right.getClass())
|| (right.getClass() != Object.class && right.getClass().isAssignableFrom(left.getClass())) //GROOVY-4046
|| (left instanceof GString && right instanceof String)
There are some restrictions for the case of equalityCheckOnly, hence when we come from the == operator. While I can not explain all of those I believe these are to prevent exceptions to be thrown under specific circumstances, such as the issue mentioned in the comment.
For brevity I omitted above that there are also cases that are handled upfront in the ScriptBytecodeAdapter and delegated to equals right away, if left and right hand side are both of the same type and one of Integer, Double or Long.

Get Parameter list of a closure dynamically in Groovy

I have a Closure defined in a groovy file that load with the shell.evaluate() method.
I need to call this closure in by calling program using the shell."$closurename".call(arguments) call.
However to formulate the closure parameters ( argument above) I'd need to now what are the arguments and arguments names that the closure $Closurename accepts. Is there a way of dynamically knowing this in Groovy? I checked in the metaClass.method property but this does not work in my example below.
Below is the example code.
def arguments;
shell.evaluate(new File("/tmp/myGroovyClosureFile.groovy"))
testBlock = "myClosureName"
//Code here to find the parameters for myClosureName and create
//the arguments variable
shell."$testBlock".call(arguments)
As Jeff mentioned, it seems like groovy when generating code for closures anonymizes somehow the parameter names. However, you can still use reflection to get as much information as you can:
def cl = { int a, String b ->
println(a)
println(b)
}
def callMethod = cl.class.methods.find {
it.name == "call"
}
println callMethod.parameterTypes
println callMethod.parameters.name
and outputs:
[int, class java.lang.String]
[arg0, arg1]
Is there a way of dynamically knowing this in Groovy?
You can't really do it dynamically at runtime.

Groovy different results on using equals() and == on a GStringImpl

According to the Groovy docs, the == is just a "clever" equals() as it also takes care of avoiding NullPointerException:
Java’s == is actually Groovy’s is() method, and Groovy’s == is a clever equals()!
[...]
But to do the usual equals() comparison, you should prefer Groovy’s ==, as it also takes care of avoiding NullPointerException, independently of whether the left or right is null or not.
So, the == and equals() should return the same value if the objects are not null. However, I'm getting unexpected results on executing the following script:
println "${'test'}" == 'test'
println "${'test'}".equals('test')
The output that I'm getting is:
true
false
Is this a known bug related to GStringImpl or something that I'm missing?
Nice question, the surprising thing about the code above is that
println "${'test'}".equals('test')
returns false. The other line of code returns the expected result, so let's forget about that.
Summary
"${'test'}".equals('test')
The object that equals is called on is of type GStringImpl whereas 'test' is of type String, so they are not considered equal.
But Why?
Obviously the GStringImpl implementation of equals could have been written such that when it is passed a String that contain the same characters as this, it returns true. Prima facie, this seems like a reasonable thing to do.
I'm guessing that the reason it wasn't written this way is because it would violate the equals contract, which states that:
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
The implementation of String.equals(Object other) will always return false when passed a GSStringImpl, so if GStringImpl.equals(Object other) returns true when passed any String, it would be in violation of the symmetric requirement.
In groovy a == b checks first for a compareTo method and uses a.compareTo(b) == 0 if a compareTo method exists. Otherwise it will use equals.
Since Strings and GStrings implement Comparable there is a compareTo method available.
The following prints true, as expected:
println "${'test'}".compareTo('test') == 0
The behaviour of == is documented in the Groovy Language Documentation:
In Java == means equality of primitive types or identity for objects. In Groovy == means equality in all cases. It translates to a.compareTo(b) == 0, when evaluating equality for Comparable objects, and a.equals(b) otherwise. To check for identity (reference equality), use the is method: a.is(b). From Groovy 3, you can also use the === operator (or negated version): a === b (or c !== d).
The full list of operators are provided in the Groovy Language Documentation for operator overloading:
Operator
Method
+
a.plus(b)
-
a.minus(b)
*
a.multiply(b)
/
a.div(b)
%
a.mod(b)
**
a.power(b)
|
a.or(b)
&
a.and(b)
^
a.xor(b)
as
a.asType(b)
a()
a.call()
a[b]
a.getAt(b)
a[b] = c
a.putAt(b, c)
a in b
b.isCase(a)
<<
a.leftShift(b)
>>
a.rightShift(b)
>>>
a.rightShiftUnsigned(b)
++
a.next()
--
a.previous()
+a
a.positive()
-a
a.negative()
~a
a.bitwiseNegate()
Leaving this here as an additional answer, so it can be found easily for Groovy beginners.
I am explicitly transforming the GString to a normal String before comparing it.
println "${'test'}".equals("test");
println "${'test'}".toString().equals("test");
results in
false
true

Enhanced collections methods on an Iterator

Is it possible to use the enhanced Collections methods that Groovy provides, like findAll and Collect with an iterator (of class java.util.Iterator) ?
Most of the enhanced methods (including findAll and collect) do work with iterators. You can test it out in the console:
assert [1,2,3].iterator().findAll{ it % 2 } == [1,3]
assert [1,2,3].iterator().collect{ it * 2 } == [2,4,6]
Check out DefaultGroovyMethods for a list of the extra methods groovy provides. In general, whenever your class is an instance of the first arg's type, that method applies to your class. In the case of collect and findAll, iterator uses the Object version. Others, like collectMany have an iterator specific version.

What is the use of "use" keyword/method in groovy?

I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException fallback) {
return (self << operand).toString()
}
}
}
use (StringCalculationCategory) {
assert 1 == '1' + '0'
assert 2 == '1' + '1'
assert 'x1' == 'x' + '1'
}
With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?
See the Pimp My Library Pattern for what use does.
In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.
use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.
By the way, this post in Dustin Marx's blog Inspired by Actual Events states:
The use "keyword" is actually NOT a keyword, but is a method on
Groovy's GDK extension of the Object class and is provided via
Object.use(Category, Closure). There are numerous other methods
provided on the Groovy GDK Object that provide convenient access to
functionality and might appear like language keywords or functions
because they don't need an object's name to proceed them. I tend not
to use variables in my Groovy scripts with these names (such as is,
println, and sleep) to avoid potential readability issues.
There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.
A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.
Example:
use (TimeCategory) {
final now = new Date()
final threeMonthsAgo = now - 3.months
final nextWeek = now + 1.week
}

Resources