Groovy - Optionals


Advertisements


Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time.

When writing code in Groovy, developers are given the flexibility to provide a type or not. This can offer some simplicity in implementation and, when leveraged properly, can service your application in a robust and dynamic way.

In Groovy, optional typing is done via the ‘def’ keyword. Following is an example of the usage of the def method −

class Example { 
   static void main(String[] args) { 
      // Example of an Integer using def 
      def a = 100; 
      println(a); 
		
      // Example of an float using def 
      def b = 100.10; 
      println(b); 
		
      // Example of an Double using def 
      def c = 100.101; 
      println(c);
		
      // Example of an String using def 
      def d = "HelloWorld"; 
      println(d); 
   } 
} 

From the above program, we can see that we have not declared the individual variables as Integer, float, double, or string even though they contain these types of values.

When we run the above program, we will get the following result −

100 
100.10 
100.101
HelloWorld

Optional typing can be a powerful utility during development, but can lead to problems in maintainability during the later stages of development when the code becomes too vast and complex.

To get a handle on how you can utilize optional typing in Groovy without getting your codebase into an unmaintainable mess, it is best to embrace the philosophy of “duck typing” in your applications.

If we re-write the above code using duck typing, it would look like the one given below. The variable names are given names which resemble more often than not the type they represent which makes the code more understandable.

class Example { 
   static void main(String[] args) { 
      // Example of an Integer using def 
      def aint = 100; 
      println(aint); 
		
      // Example of an float using def 
      def bfloat = 100.10; 
      println(bfloat); 
		
      // Example of an Double using def 
      def cDouble = 100.101; 
      println(cDouble);
		
      // Example of an String using def 
      def dString = "HelloWorld"; 
      println(dString); 
   } 
}


Advertisements