Thursday, 17 January 2019

Groovy: call operator


The call operator () is used to call a method named call implicitly.

For example,
class Factorial{

         int call(int num){
                  if(num < 0)
                           throw new IllegalArgumentException('input must be >= 0')
                 
                  if(num == 0 || num == 1)
                           return 1
                          
                  int result = 1
                  for(int i = 2; i <= num; i++){
                           result  = result * i
                  }
                 
                  return result
         }
        
}

I can call the call method like below.

Factorial factorial = new Factorial()
int result1 = factorial.call(5)

I can even call the ‘call’ method like below.
int result2 = factorial(5)

HelloWorld.groovy
class Factorial{

 int call(int num){
  if(num < 0)
   throw new IllegalArgumentException('input must be >= 0')
  
  if(num == 0 || num == 1)
   return 1
   
  int result = 1
  for(int i = 2; i <= num; i++){
   result  = result * i
  }
  
  return result
 }
 
}

Factorial factorial = new Factorial()

int result1 = factorial.call(5)
int result2 = factorial(5)

println "Factorial of 5 is ${result1}"
println "Factorial of 5 is ${result2}"

Output
Factorial of 5 is 120
Factorial of 5 is 120


Previous                                                 Next                                                 Home

No comments:

Post a Comment