1

I am new to groovy and am trying to pass a closure as a parameter to a method , below is my code , I am using Groovy 2.4

class Test
{
    def testMethod()
    {
        def cl = {a,b -> println "a = "+${a}+" b = "+${b}}
        testClosure(cl);
    }

    def testClosure(closure)
    {
        closure(5,2);
    }
}

I am getting the below exception when i am trying to execute it ,

Caught: groovy.lang.MissingMethodException: No signature of method: 
   com.gr.practice.Test.$() is applicable for argument types:
   (com.gr.practice.Test$_testMethod_closure1$_closure2) values:
   [com.gr.practice.Test$_testMethod_closure1$_closure2@3e92efc3]
Possible solutions: 
   is(java.lang.Object), 
   any(),
   any(groovy.lang.Closure),
   use([Ljava.lang.Object;),
   wait(), 
   dump()
groovy.lang.MissingMethodException: No signature of method:
   com.gr.practice.Test.$() is applicable for argument types:
   (com.gr.practice.Test$_testMethod_closure1$_closure2) values:
   [com.gr.practice.Test$_testMethod_closure1$_closure2@3e92efc3]
Possible solutions: 
   is(java.lang.Object),
   any(),
   any(groovy.lang.Closure),
   use([Ljava.lang.Object;),
   wait(),
   dump()
    at com.gr.practice.Test$_testMethod_closure1.doCall(Test.groovy:10)
    at com.gr.practice.Test.testClosure(Test.groovy:16)
    at com.gr.practice.Test$testClosure$0.callCurrent(Unknown Source)
    at com.gr.practice.Test.testMethod(Test.groovy:11)
    at com.gr.practice.Test$testMethod.call(Unknown Source)
    at com.gr.practice.main.run(main.groovy:7)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Could anyone please help ?

Daniel A. Thompson
  • 1,904
  • 1
  • 17
  • 26
Tushar Kumar
  • 65
  • 2
  • 7

1 Answers1

1

Your problem is println "a = "+${a}+" b = "+${b}. You probably want this:

println "a = ${a} b = ${b}"

Or:

println "a = " + a + " b = " + b

(the former is a better idea)

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • Thanks for your reply Jeff , although doing the same fixes it in Intellig Idea but facing the same problem in eclipse with groovy-eclipse plugin , below is the improvised code , `def static main(String[] args) { def cl = { a,b -> println "a = ${a} and b = ${b}"} testClosure(cl) } private def testClosure(closure) { closure(5,2) }` Do you have a clue why this might be happening ? – Tushar Kumar Jun 26 '16 at 15:09
  • `println "a = ${a} b = ${b}"` is valid Groovy code, regardless of what IDE you are using. If the IDE complains about it for some reason, that is an IDE bug. That is valid code. – Jeff Scott Brown Jun 27 '16 at 03:24