尝试将闭包作为参数传递时,groovy.lang.MissingMethodException

时间:2016-06-26 13:57:10

标签: groovy

我是groovy的新手,我试图将闭包作为参数传递给方法,下面是我的代码,我使用的是Groovy 2.4

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

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

当我尝试执行它时,我得到以下异常,

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)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您的问题是println "a = "+${a}+" b = "+${b}。你可能想要这个:

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

或者:

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

(前者是个更好的主意)

相关问题