Tuesday, July 22, 2014

Java vs Groovy : The Ternary Operator

The Ternary Operator is used to convert simple if-then-else blocks...
if(true) {
   // do this
}
else {
   // do that
}
...into a single statement, like so.
true ? doThis() : doThat();
Java requires that each part of the ternary operator returns something and that that something is stored in a variable.  For example, suppose you had the following Java class ...
public class FooBar {

   public boolean isTrue() {
      return true;
   }

   public void doNothing() {
   }
}
Since the then-else parts of the ternary operator must return something, the following statement will result in a compiler error.
isTrue() ? doNothing() : doNothing(); // compiler error
Likewise, the result of the ternary operator must be stored in some variable.
// isTrue() ? isTrue() : isTrue(); // compiler error
boolean result = isTrue() ? isTrue() : isTrue(); // valid
Groovy, on the other hand, is different from Java in that the then-else parts of the ternary operator don't have to return anything. You don't even have to store the result of the ternary operator in some variable. So all of the above is valid code in Groovy.

You don't even have to use the same data types for both the then-else parts. For example:
true ? 5 : "Hello World"

No comments:

Post a Comment