Showing posts with label closures. Show all posts
Showing posts with label closures. Show all posts

Sunday, 27 January 2019

Groovy: Closure: Currying


Currying is a process of transforming multi argument functions into a function that takes fewer arguments by fixing some values, named for the British mathematician and logician Haskell Curry.

Example
def sum = {a, b -> a + b}
def incByOne = sum.curry(1)

As you see above snippet, I defined the function incByOne by fixing the first argument of closure ‘sum’ to 1.

HelloWorld.groovy
def sum = {a, b -> a + b}
def incByOne = sum.curry(1)

def result = incByOne(10)

println "result : $result"

Output
result : 11




Previous                                                 Next                                                 Home

Groovy: closure.getParameterTypes().size(): Check number of arguments this closure takes


‘closure.getParameterTypes().size()’ return number of arguments supplied to the closure.

HelloWorld.groovy
def performAction(Closure closure){
 int size = closure.getParameterTypes().size()
 
 if(size == 1){
  println "Closure takes one argument"
 }else if(size == 2){
  println "Closure takes two arguments"
 }else{
  println "Closure takes more than two arguments"
 }
}

performAction {x -> x * x}
performAction {x, y -> x + y}
performAction {x, y, z -> x + y + z}

Output
Closure takes one argument
Closure takes two arguments
Closure takes more than two arguments



Previous                                                 Next                                                 Home