Thursday 17 January 2019

Groovy: Coercion operator (as)


Coercion operator is used to convert one object to other. Objects no need to be compatible.

How to perform coercion?
By specifying the Coercion rule, we can convert two incompatible objects.

For example, I specify the asType method, it convers the Employee object to Person object.

class Employee{
         String firstName
         String lastName
         String id
        
         def asType(Class target) {                                             
        if (target == Person) {
            return new Person(name: firstName + "," + lastName, id : id)
        }
        throw new ClassCastException("Employee cannot be coerced into $target")
    }
}

HelloWorld.groovy

class Employee{
 String firstName
 String lastName
 String id
 
 def asType(Class target) {                                              
        if (target == Person) {
            return new Person(name: firstName + "," + lastName, id : id)
        }
        throw new ClassCastException("Employee cannot be coerced into $target")
    }
}

class Person{
 String name
 String id
}

Employee emp = new Employee(firstName : "Krishna", lastName : "Gurram", id : "Id123")
Person person = emp as Person

println "name : ${person.name}, id : ${person.id}"

Output
name : Krishna,Gurram, id : Id123

Previous                                                 Next                                                 Home

No comments:

Post a Comment