Friday, September 7, 2012

Say hello to Groovy – Part 2 (Operators & Control Structures)

In my last blog, I gave an introduction to Groovy. We looked at the typical hello world program in Java as well as Groovy to understand how some of the additional features provided by Groovy helps to cut down on a lot of boilerplate code that you would have otherwise written in Java. In this blog, I will concentrate on some of the operators and control structures which are unique to Groovy.

Groovy Truth

Like Java, Groovy supports standard conditional operators in a Boolean expression. In addition to this, any type can be evaluated as a Boolean expression in Groovy. This is possible because Groovy has rules to convert a non-boolean objects to a Boolean value. E.g. In case of string, non-empty strings evaluate to true

String str = …
//Java
If(str != null && !str.isEmpty())
{
//do something with str
}
//Groovy
If(str)
{
//do something with str
}
view raw ex1.groovy hosted with ❤ by GitHub

Following are some of the rules that you should know: 
1. Empty collection evaluates to false. 
2. Non-zero numbers evaluates to true. 
3. A non-null object reference evaluates to true. 
4. Non-empty Map evaluates to true. 
5. Iterators/enumerators evaluates to false if it has no further elements. 

Operator Overloading

In Java we use the == operator to see if the variables are referring to the same object instance. Groovy overrides == operator on types such as String, Integer, List etc., to check for content equality rather than object equality. To test if two variables are referring to the same object instance in Groovy we use the is () method.



String str1 = new String("example 1")
String str2 = new String("example 1")
if(str1 == str2){
println("str1 and str2 has same content")
}
if(str1.is( str2)){
println("str1 and str2 points to same object reference")
}
view raw ex2.groovy hosted with ❤ by GitHub


Elvis Operator (?:)


The "Elvis operator" is similar to Java's ternary operator. It can be used for returning a 'sensible default' value if an expression resolves to false or null. E.g. In below snippet, if username is null or empty, “Anonymous” would get printed. 

String userName;
println( userName ? userName : "Anonymous") //traditional ternary operator usage
println( userName ?: "Anonymous" ) // Elvis operator - does same as above
userName = "John"
println( userName ?: "Anonymous" )
view raw ex3.groovy hosted with ❤ by GitHub

Safe Navigation Operator (?.)


In Java, it’s a common practice to check for null, before invoking a method on the object to avoid NullPointerException. In Groovy, this is achieved in lesser lines of code using the Safe Navigation operator. The safe navigation operator will simply return null instead of throwing an exception, e.g: In the below code snippet, null would get printed and no NPE will be thrown.

class User
{
String fName;
static main( args){
User user;
println (user?.fName)
}
}
view raw ex4.groovy hosted with ❤ by GitHub


Looping

In addition to all looping constructs available in Java, Groovy provides some extra ways to loop and execute a piece of code. Groovy extends the Integer class with the step (), upto () and times () methods. If we have a List in Groovy we can loop through the items on the list with the each () and eachWithIndex () methods. We will revisit this with examples when I cover closure and collections.


Exception Handling

Groovy doesn’t force you to handle exceptions within the method signature not even for checking exceptions. You are free to choose how and when you handle the exception. The exception is passed on to the calling code until it is handled. E.g. the following is a valid code in Groovy however if you were to write the same code in Java, the compiler would have forced you to handle java.net.MalformedURLException.

class Test
{
static main( args){
URL url = new URL("http://www.yahoo.com")
}
}
view raw ex5.groovy hosted with ❤ by GitHub

No comments:

Post a Comment