简体   繁体   English

在闭包内调用 Groovy 闭包时出现 MissingMethodException

[英]MissingMethodException while calling Groovy closure inside closure

I have a groovy script which looks similar like below:我有一个类似于下面的 groovy 脚本:

def clouser = {
    def clouserOne = { _argsA  -> 
        def clouserTwo = { _argsB ->
            // Do Something with _argsA and _argsB
            println(_argsA)
            println(_argsB)
        }
    }
} 

while calling this在调用这个时

clouser().clouserOne("A").clouserTwo("B")

I am getting an error我收到一个错误

groovy.lang.MissingMethodException: No signature of method: Script1.clouserOne() is applicable for argument types: (String) values: [A]
    at Script1.run(Script1.groovy:11)

What is the correct way to define this kind of closure inside closure?在闭包中定义这种闭包的正确方法是什么? And how to call it in a proper way?以及如何以正确的方式调用它?

The problem with the original code is, that you are defining just some local variables, that never get used.原始代码的问题在于,您只定义了一些从未使用过的局部变量。 Instead the assigned closure is returned directly.而是直接返回分配的闭包。

To make your original code work, you can call:要使您的原始代码工作,您可以调用:

closure()("A")("B")

(Each closure call returns the next closure and you just chain the calls; of course there is no need to have the def clouserXXX in there). (每个闭包调用都会返回下一个闭包,您只需将调用链接起来;当然,那里不需要def clouserXXX )。

If you leave the only def out, you will create "global vars" and that is most likely not what you want.如果您将唯一的def排除在外,您将创建“全局变量”,这很可能不是您想要的。

If you want to have the names in there, you have to return something with the names.如果你想把名字放在那里,你必须返回一些带有名字的东西。 One simple example is using maps as the return.一个简单的例子是使用地图作为回报。 Eg:例如:

def closure = { ->
    [closureOne: { _argsA  -> 
        [closureTwo: { _argsB ->
            println(_argsA)
            println(_argsB)
        }]
    }]
} 

closure().closureOne("A").closureTwo("B")

After some more reading, I came across more complex closure of closure which will accepts a closure and get executed inside closure.经过更多阅读,我遇到了更复杂的闭包闭包,它将接受一个闭包并在闭包内执行。 For example:例如:

someClouser = {_args -> _args }

clouser = {
    clouserOne = { String _argOne -> 
        clouserTwo = { String _argTwo, Closure c={any()} -> 
            print "Use _argOne: ${_argOne} and _argTwo : ${_argTwo} and invoke passed clouser ${c.call()} this way" 
        }
    } 
}.call()

and it can be call or use like它可以被调用或使用

clouser.clouserOne("IMAGE").clouserTwo("INSIDE") ​{ 
     someClouser "Hello World" 
}​​​

The result will be结果将是

Use _argOne: IMAGE and _argTwo : INSIDE and invoke passed clouser Hello World this way

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM