Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Optional Parenthesis



Optional Parenthesis is a distinctive syntactic sugar feature of Groovy. It makes code more consise and readable. This feature is quite useful while working on Domain Specific Languages, DSLs. In this chapter, we're exploring optional parenthesis in details with examples.

Methods with Single Argument

We can omit parenthesis when a method is accepting a single argument. Following is a simple example demonstrating the same.

Example.groovy

class Example {
   def greet(String user) {
      println "Hello" + user + "!"
   } 
	
   static void main(String[] args) {
      Example example = new Example()
	  // call function with parenthesis
	  example.greet("Robert")
	  
	  // call function without parenthesis
	  example.greet	"Robert"
   } 
}

Output

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

HelloRobert!
HelloRobert!

Methods with Multiple Arguments

We can omit parenthesis when a method is accepting multiple arguments but it may reduce the readability. Following is a simple example demonstrating the same.

Example.groovy

class Example {
   def add(a, b) {
      return a + b  
   } 
	
   static void main(String[] args) {
      Example example = new Example()
	  // call function with parenthesis
	  println example.add(2, 3)
	  
	  // call function without parenthesis
	  println(example.add 2, 3)
   } 
}

Output

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

5
5

Closure as Argument

We can omit parenthesis when a method is accepting a closure as last argument.

Example.groovy

class Example {
   def static repeat(int times, Closure action) {
      for (int i = 0; i < times; i++) {
         action.call(i)
      }
   }

   static void main(String[] args) {
      // call the function with parenthesis      
      repeat(3, { index -> println "Iteration: ${index}" })  
      // call the function without parenthesis
      repeat(3) { index -> println "Iteration: ${index}" }   
   } 
}

Output

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

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 0
Iteration: 1
Iteration: 2
Advertisements