使用带有CliBuilder的`with`时出现意外行为

时间:2016-03-09 17:53:52

标签: groovy

给出一个脚本test.groovy

def cli = new CliBuilder().with {}
println cli

cli = new CliBuilder()
cli.with {}
println cli

当我运行groovy test.groovy时,输出为

null
groovy.util.CliBuilder@3c22fc4c

为什么第一个输出行null?这是我的groovy --version信息:

Groovy Version: 2.4.3 JVM: 1.8.0_40 Vendor: Oracle Corporation OS: Mac OS X

2 个答案:

答案 0 :(得分:2)

它是null,因为with(Closure c)应该返回delegate(此处代理是CliBuilder的实例),该cli将分配给def cli = new CliBuilder().with { it } 。用作:

    public void GetUpdates() throws Exception {
    URL website = new URL(Configration.UpdatesUrl);
    URLConnection connection = website.openConnection();
    BufferedReader in = new BufferedReader(  new InputStreamReader( connection.getInputStream()));
    StringBuilder response = new StringBuilder();
    String inputLine;
    String info = "";
    int startLine = 1;
    int endLine = 50;
    for (int i = 0; i < startLine; i++) { 
        info = in.readLine(); 
    }
    for (int i = startLine; i < endLine + 1; i++) {
        info = in.readLine();
        System.out.println(info);
    }
    UpdateText.setText(info);
    in.close();
}

答案 1 :(得分:0)

您没有从传递给with方法的闭包中返回任何内容,因此with返回null,而第一个示例中的cli变为null