开发者

PropertyMissing for MethodClosure

开发者 https://www.devze.com 2023-03-02 10:11 出处:网络
When I try this code in groovysh: def foo(s) { s.trim() } a = foo everything works as expected, but when I try it in IDE (Intellij idea) I get:

When I try this code in groovysh:

def foo(s) {
    s.trim()
}

a = foo

everything works as expected, but when I try it in IDE (Intellij idea) I get:

Caught: groovy.lang.MissingPropertyException: No such property: foo for class: Test
a开发者_如何转开发t Test.run(Test.groovy:5)

EDIT: Same with Eclipse.

Is there any secret how groovysh converts methods to closures?

Unfortunately, I can't use the usual this.&foo syntax as the code is a part of DSL and i would like to make it less verbose.

Groovy 1.8


It doesn't work for me in the groovy console and I wouldn't expect it to, because foo is a function and you're trying to store a reference to it in the variable a. You can only store references to closures in variables, so you should either redefine foo as a closure

def foo = {s ->
    s.trim()
}

a = foo

or define it as a function and use the .& operator to convert it to a closure

def foo(s) {
    s.trim()
}

a = this.&foo


In groovysh's Interpreter.groovy there is a line:

context["${m.name}"] = new MethodClosure(type.newInstance(), m.name)

I think it answers my question.

0

精彩评论

暂无评论...
验证码 换一张
取 消