Groovy Quiz 16 | Closures


Reference video | Groovy Playground


1 Point for every correct answer | Let’s Get Started

1.

Guess the output

def myClosure1 = { print "Hello World" }
myClosure1.call()
 
 
 

2.

//closure with parameter

def myClosure1 = { name -> print "Hello ${name}" }
myClosure1.call("Raghav")
 
 
 

3.

//Diff between method and closure

def str = "Hello "
def myClosure1 = { name -> print "$str ${name}" }
myClosure1.call("Raghav")

def myMethod1(){
    println "$str"
}
myMethod1()
 
 
 

4.

Closure can be passed as a variable in a method

def str = "Hello"
def myClosure1 = { name -> print "$str ${name}" }

def myMethod1(clos){
    clos.call("Groovy")
}
myMethod1(myClosure1)
 
 
 

5.

Return in closure

def myClosure = {
    a,b,c ->
    return (a+b+c)
}
print myClosure(1,2,3)
 
 
 

6.

//using closure to print list elements

def myList = ["Apples", "Oranges", "Grapes"]
print myList.each { it }
 
 

7.

Using closures to print Map

def myMap = [
    'name'  :   'Raghav',
'subject'   :   'Groovy'
    ]    
print myMap.each { it }
 
 
 

8.

Using closure to find element in a list

def myList = [1,2,3,4,5]
print myList.find { item -> item == 3}
 
 
 

9.

Using closure to find an element in a list

def myList = [1,2,3,4,5]
print myList.find { item -> item == 7}
 
 
 

10.

findAll

def myList = [1,2,3,4,5]
print myList.findAll { item -> item > 3}
 
 
 

11.

//any

def myList = [1,2,3,4,5]
print myList.any { item -> item > 3}
 
 
 

12.

//Every

def myList = [1,2,3,4,5]
print myList.every { item -> item > 3}
 
 

13.

updating list items and storing

def myList = [1,2,3,4,5]
print myList.collect { item -> item * 3}
 
 
 

7