使用闭包调用忽略方法params。

时间:2014-03-22 15:49:53

标签: groovy

我有一个这样的课程:

class Test
{
    def method(def args)
    {
        println args
    }
}

我做了:

def test = new Test()
test.with{
    method([1:1])
}

按预期工作。但我想要的是在没有参数的情况下调用method,如果我这样做:

method [1:1]

我收到以下错误:

You tried to use a map entry for an index operation, this is not allowed. Maybe something should be set in parentheses or a comma is missing?
 at line: 13, column: 13

我可以在没有参数的情况下调用该方法吗?这可能吗?

1 个答案:

答案 0 :(得分:0)

如果没有括号,它就好像是按索引访问列表元素。

method [1:1] --> method[1:1]

并抱怨索引不是数字而是地图条目。所以你可以尝试:

test.with{
    def map = [1:1]
    method map

    //or just
    method 1:1
}
相关问题