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() Hello World No output Exception 2. //closure with parameter def myClosure1 = { name -> print "Hello ${name}" } myClosure1.call("Raghav") No output Hello name Hello Raghav 3. //Diff between method and closure def str = "Hello " def myClosure1 = { name -> print "$str ${name}" } myClosure1.call("Raghav") def myMethod1(){ println "$str" } myMethod1() Hello Raghav Hello Hello Raghav Exception Exception 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) Hello Groovy Hello name Exception 5. Return in closure def myClosure = { a,b,c -> return (a+b+c) } print myClosure(1,2,3) 7 6 Exception 6. //using closure to print list elements def myList = ["Apples", "Oranges", "Grapes"] print myList.each { it } [Apples, Oranges, Grapes] Exception 7. Using closures to print Map def myMap = [ 'name' : 'Raghav', 'subject' : 'Groovy' ] print myMap.each { it } {name=Raghav, subject=Groovy} name=Raghav subject=Groovy Exception 8. Using closure to find element in a list def myList = [1,2,3,4,5] print myList.find { item -> item == 3} true 3 Exception 9. Using closure to find an element in a list def myList = [1,2,3,4,5] print myList.find { item -> item == 7} exception null 7 10. findAll def myList = [1,2,3,4,5] print myList.findAll { item -> item > 3} [4, 5] [3, 4, 5] exception 11. //any def myList = [1,2,3,4,5] print myList.any { item -> item > 3} [4,5] true exception 12. //Every def myList = [1,2,3,4,5] print myList.every { item -> item > 3} true false 13. updating list items and storing def myList = [1,2,3,4,5] print myList.collect { item -> item * 3} [3, 6, 9, 12, 15] Exception [1, 2, 3, 4, 5] Loading … 7 Share this:TwitterFacebookLinkedIn Related