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.
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.
Published at DZone with permission of Alex Staveley, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Auto-Scaling Kinesis Data Streams Applications on Kubernetes
-
Micro Frontends on Monorepo With Remote State Management
-
Five Java Books Beginners and Professionals Should Read
-
Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
Comments