Skip to main content

Posts

Showing posts with the label Groovy Operators

Groovy : What is Coercion operator and how to use it

Point to Remember Coercion Operator is used for casting Custom Coercion rules can be applied to a class by defining asType method in a class. 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...

Groovy : What is Elvis Operator and difference b/w Elvis and Ternary operator

Ternary Operator Ternary Operator is the short hand of the if-else block , where a condition is evaluated to true or false and following statement is executed. Syntax of the ternary operator is below < boolean expression> ? <executed when condition is true > : <executed when condition is false > A typical example of if-else block is shown below where we check if a variable is null or not. String s = "hello" if ( s != null ) println s else println "not found" We can replace the above code with the ternary operator as shown below String s = "hello" println s != null ? s : "not found" Here, the variable s is assigned a string hello and condition s!=null evaluates to true hence the statement after ? is executed which returns s itself. Elvis Operator Elvis operator is the short hand of the Ternary operator explained above. In t...

Groovy : What is Safe Navigation operator or Null check Operator

Safe navigation operator The safe navigation Operator is used to avoid null pointer exceptions. Many a times you come across the need to access the value of an object if it is not null. Syntax for the Safe Navigation Operator is <object>?.<property> Here the could be any object and could be any property of the object. Let's have a look at the below example, class User { String name; } User u = new User(name : "ekiras" ) if (u != null ) println u.name // prints ekiras In the above code we have to write the if block to check if the user object is null or not. So, with the Safe navigation operator we do not need to write the if-else blocks. We can rewrite the above code as shown below class User { String name; } User u = new User( name : "ekiras" ) println u?.name // prints ekiras