Gotchas

We’ll see a number of nice Groovy capabilities throughout this book, but some “gotchas“ do exist, ranging from minor annoyances to potential surprises. In the following sections, we’ll explore a few of them.

Groovy’s == Is Equal to Java’s equals

== and equals are a source of confusion in Java, and Groovy adds to the confusion. Groovy maps the == operator to the equals method in Java. What if we want to actually perform the reference equals (the original ==, that is)? We have to use is in Groovy for that. Let’s understand the difference via an example:

GroovyForJavaEyes/Equals.groovy
 
str1 = ​'hello'
 
str2 = str1
 
str3 = ​new​ ​String​(​'hello'​)
 
str4 = ​'Hello'
 
 
println ​"str1 == str2: ​${str1 == str2}​"
 
println ​"str1 == str3: ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.