Groovy : What is Coercion operator and how to use it

Point to Remember

  1. Coercion Operator is used for casting
  2. Custom Coercion rules can be applied to a class by defining asType method in a class.
  3. Syntax of coercion operator is as

What is Coercion Operator

Coercion operator is used to do type casting of objects in groovy. It converts objects of one type to another type.

Lets take a look at the following examples

int a = 123
String s = (String) a

The the above example, the assignment of a to s will give a ClassCastException in java but when you run the same in groovy it will not give an error since Groovy as defined how to typecast integer to string.

Coercion version of the above example is as follows

int a = 123
String s =  a as String

How to Define Custom Coercion Rules.

Let's take an example where we want to convert an object of class A to class B.

class A{
  String name
}

class B{
  String name
  String email
  
  def asType(Class target){
    if(target == A)
      return new A(name : this.name)
    if(target == String)
     return new String("${this.name }  ${this.email}")  
  }
}

def b = new B(name : 'ekansh', email : 'ekansh@ekiras.com')

def a = b as A
def s = b as String

println b.dump()
println a.dump()
println s
Output

<B@6040d37b name=ekansh email=ekansh@ekiras.com>
<A@b0fb0cc name=ekansh>
ekansh ekansh@ekiras.com


Here the important thing to note is the asType() method. In asType you can return the any object since the return type of the method is def. You can return object of any class depending upon the type of class it has to be casted to

When the as A is called on object of class B, then an object of class A will be returned. When as String is called on object of class B is called then a String object is returned.

No comments:

Powered by Blogger.