English 中文(简体)
Groovy - Optionals
  • 时间:2024-09-17

Groovy - Optionals


Previous Page Next Page  

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 flexibipty to provide a type or not. This can offer some simppcity in implementation and, when leveraged properly, can service your apppcation 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 inspanidual 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 utipty during development, but can lead to problems in maintainabipty during the later stages of development when the code becomes too vast and complex.

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

If we re-write the above code using duck typing, it would look pke 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