DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Groovy's Smooth Operators

Groovy's Smooth Operators

We'll leave the 1980's comparisons there and shall discuss a few of the smooth operators in Groovy in this blog post.

Alex Staveley user avatar by
Alex Staveley
·
Jan. 02, 14 · Tutorial
Like (5)
Save
Tweet
Share
26.80K Views

Join the DZone community and get the full member experience.

Join For Free

Take a trip back to 1984.  Apple released the Macintosh, 'The Final Battle' is about to commence in V and Scotland won the Five Nations completing a grand slam in the process.  Right in the middle of miners' strike in the UK, English pop group Sade released the catchy number: Smooth Operator.  It was chart success in the UK and in the US (not to mention the German, Dutch and Austrian charts). Little did Sade know that decades later the Groovy programming language would feature several smooth operators that go above and beyond the standard set of Java operators.  Now, we'll leave the 1980's comparisons there and shall discuss a few of the smooth operators in Groovy in this blog post.

Elvis 

The Elvis Operator (so named after a certain person's hairstyle) is a shortened version of the ternary operator.  It is very handy for null checking. And remember even though it can be argued null handling is bad coding practise because it is better to not have nulls in your code, lots of APIs in a code base will inevitably return nulls and in the real world where you want to add some robustness and defensive coding to keep things smooth in production, this can of thing can be useful.

Now here is how it works.  If the expression to the left of the Elvis operator evaluates to false (remember in Groovy there are several things such as null, such as an empty String which can be coerced to mean false), the result of the expression will be the whatever is on the right. 

?
String country = country.name ?: "Unknown country"

So, in the above example if country.name is null or just "" since both are false in Groovy, country will be assigned as "Unknown country".   If country.name was non - false, country would just be assigned that value.

Null-Safe Dereference (also called the Safe Navigation operator) 

This is especially useful to avoid null pointer exceptions in a chained expression. For example,

?
String location = map.getLocation().getXandYCoordinates();

might yield a null pointer exception. But using the safe navigation operator if either map, or the result of map.getLocation() are null 

?
String location = map?.getLocation()?.getXandYCoordinates(); 

location will just be set as null. So, no null pointer exception is thrown.

Spread 

The Spread operator is useful when executing a method on elements of a collection and collecting the result. In this example, I parse a bunch of Strings into arrays and then run a closure on each of the arrays to get all the first elements. 

?
def names = ["john magoo","peter murphy"]
def namesAsArrays = names*.split(" ")
namesAsArrays.each(){printit[0]}

Now, remember the Spread operator can only be used on methods and on elements. It can't execute a closure for example. But what we can do is leverage Groovy's meta programming capabilities to create a method and then use the spread operator to invoke that. Suppose we had a list of numbers that we wanted to add 50 too and the multiply the answer by 6 we could do:

?
def numbers = [43,4]
java.lang.Integer.metaClass.remixIt = {(delegate + 50) * 6}
numbers*.remixIt()

Spaceship Operator 

This originated in the Perl programming language and is so called because you guessed it, <=> looks like a spaceship!  So how does it work?  Well, it is like this.  The expression on the left and the right of the spaceship operator are both evaluated.   -1 will be returned if operand on left is smaller, 0 if the left and right are equal and 1 if the left is larger. It's power should become more obvious with an example.

Say we have a class to represent software engineers. 

?
class SoftwareEngineer {
String name
int age
String toString() { "($name,$age)"}
}
def engineers = [
new SoftwareEngineer(name: "Martin Fowler", age: 50),
new SoftwareEngineer(name: "Roy Fielding", age: 48),
new SoftwareEngineer(name: "James Gosling", age: 58)
]

Now we could easily sort by age 

?
engineers.sort{it.age}

But what about when our list of Engineers grows and grows and we have multiple engineers of the same age? In these scenarios it would be nice to sort by age first and name second. We could achieve this by doing: 

?
class SoftwareEngineer {
engineers.sort{a, b ->
a.age <=> b.age ?: a.name <=> b.name
}

This expression will try to sort engineers by age first. If their ages' are equal a.age <=> b.age will return 0. In Groovy and in the Elvis construct, 0 means false and a.name <=> b.name will be then evaluated and used to determine the sort.

Field Access 

In Groovy, when a field access is attempt, Groovy will invoke the corresponding accessor method. The Field Access operator is a mechanism to force Groovy to use field access.

?
class RugbyPlayer {
String name
String getName() {name ?: "No name"}
}
assert "Tony"== newRugbyPlayer(name: "Tony").name
assert "No name"== newRugbyPlayer().name
assert null== newRugbyPlayer().@name

Method Reference 

The Method Reference operator allows you to treat a reference to a method like a closure. 

?
class MyClass {
void myMethod() { println"1"}
void myMethod(String s) { println"2"}
}
def methodRef = newMyClass().&"myMethod"
methodRef()  // outputs 1
methodRef('x') // outputs 2

The .& creates an instance of org.codehaus.groovy.runtime.MethodClosure. This can be assigned to a variable and subsequently invoked as shown. 

Happy New Year to you all and hopefully some more blogging in 2014.

Operator (extension) Groovy (programming language)

Published at DZone with permission of Alex Staveley, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • SAST: How Code Analysis Tools Look for Security Flaws
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • Connecting Your Devs' Work to the Business
  • Three SQL Keywords in QuestDB for Finding Missing Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: