Posts Tagged ‘Safe Navigational Operator

Operator ad-hoc Polymorphism in Groovy

with 2 comments

Operator ad-hoc polymorphism most commonly known as Operator Overloading, expresses about the polymorphic(more than one)  behaviour exhibited by the operator at different contexts.

In Groovy, this behaviour depends on the operands on both sides.

Let’s look at it.

def a="ten"; b=2.5; c=3; d=[]; e=[:]

//Case 1
assert result=='ten2.5'
println result.getClass()                    //O/P: class java.lang.String

//Case 2
assert result==5.5
println result.getClass()                    //O/P: class java.math.BigDecimal

//Case 3
println c.getClass()                        //O/P: class java.lang.Integer
assert c==50000000000003
println c.getClass()                        //O/P: class java.lang.Long
println c.getClass()                        //O/P: class java.math.BigInteger

//Case 4
assert d==[100]

assert e==['A':1,'B':2,'C':3]

//Case 5
def f='!'
println f*10                               //O/P: !!!!!!!!!!
assert f*10==f.multiply(10)

In the above code, each variable is of different type and the operator behaves accordingly.

  • Case 1: + Operator appends the BigDecimal value to a String and the result is of String type. 
    In Groovy, a decimal number, by default is of BigDecimal type. Instead of + operator,  . plus() method can also be used.

Like .plus(),  there are various methods corresponding to a particular operator function. You can check it out over here.

  • Case 2: + Operator performs the operation of summing a BigDecimal value and and an Integer. Here the result type is BigDecimal.
  • Case 3: Before going into the third case, let’s get to know of something…

When I assign a number value to a def variable, groovy takes into account, the smallest variable type that accomodates that particular value.

Here in this case of c , the type is Integer. As the size of the variable increases , it would make it the instance of Long or BigInteger which are of greater sizes. Therefore the order is Integer–> Long–> BigInteger.

  • Case 4:+ Operator performs the action of adding elements to the list d and map e.
  • Case 5: If we want to print a String n number of times, it can be done by multiplying the String by an integer as shown in above code case 5.

In all the above cases,we can see that, an operator decides its nature of operation  based upon the behaviour and type of the operands.

== and .equals():

In groovy, == and .equals carry the same meaning.  It checks for value equality.

def a='abcd'
println a=='abcd'                  //O/P: true
println a.equals('abcd')           //O/P: true

But == and .equals are not the same in GString Implementation.

def a='abcd'
println "$a"=='abcd'               //O/P: true
println "$a".equals('abcd')        //O/P: false

GStrings are again behaving in a strange way.

The reason is that, GString’s .equals() method takes in argument that is an instance of GString and not of any other type, be it even a String.


Groovy has provided us an extra flexibility with handling the ever torturing NullPointerException.

Let’s see how…

a=null         // Null Pointer Exception thrown
result=a?.plus(8)        // O/P: null

In the above case , we can see that ,

SAFE NAVIGATIONAL OPERATOR ‘?’ checks null and prevents NullPointer Exception to be thrown.

Safe Navigational Operator shouldn’t be followed by another operator. If done so , it wont work.


Here a sequence of elements are got  when the Lowest value and the Highest Value is specified.. The sequence can be a sequence of number/ character .

Ranges extend java.util.List class.

Range Object is a List Object. i.e., the output is obtained in List form.

Range is defined as below,

def a=10..7
assert a==[10,9,8,7]

It can also be defined by using a spread operator(*).

def b=[*'a'..'h']
assert b==['a','b','c','d','e','f','g','h']

Here spread operator  extracts and spreads individual values in the form of a List object.


class GreWordDetails{
    String greWord
    String wordMeaning
    def explanation(){
     "$greWord means $wordMeaning"
def wordList=[
      new GreWordDetails(greWord:'abash',wordMeaning:'ashamed'),
      new GreWordDetails(greWord:'enigma',wordMeaning:'mystery')
println wordList*.explanation()

O/P:[abash means ashamed, enigma means mystery]

It is said , The spread-dot operator (*.) is used to invoke a method on all members of a Collection object.

In the above code,  this operator invokes the explanation() method on the members of wordList object and spreads the result.

ELVIS Operator(?:):

This operator is a CUT SHORT form of TERNARY OPERATOR

b=(a!=null)?a:false can also be written as b=a?:false

Groovy Operators are not just this.. There are lots of other things like Spacechip Operator, EXOR, AND, OR,Power Operator and etc.,

Have a nice day 🙂