Groovy eachWithIndex多个语句

时间:2019-05-22 16:33:48

标签: groovy

我找到了这个例子 https://stackoverflow.com/a/5591274/4587961

但是它只有一条语句

def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" }

如何执行多条语句

例如

def functionWithMultipleStateements(Object o, int index) {
    int a = 2;
    int b = 3;
    println (a + b)
    println o
    println index
}

numbers.eachWithIndex{ num, idx -> functionWithMultipleStateements "$idx: $num" }

效果很好。但是,当我尝试

numbers.eachWithIndex{ num, idx ->  
    {
        int a = 2;
        int b = 3;
        println (a + b) + " " + "$idx: $num"
    }
}

编译失败。我不想声明其他功能。

1 个答案:

答案 0 :(得分:2)

以下代码:

class MyTreeView(ttk.Treeview):
    def __init__(self, master=None, my_list=[], **kw):
        super(MyTreeView, self).__init__(master=master, **kw)

        # Level 1
        PARENT="" # top level
        INDEX = 1 # insert at end
        i = 0

        for thing in my_list:
            self.insert(PARENT, INDEX, i, text=str(i), values=(thing))

        self.bind("<Double-1>", self.OnFeatureDoubleClick)

    def OnFeatureDoubleClick(self, event):
        print ("MyTreeView.OnFeatureDoubleClick: self: " + str(self))
        print ("MyTreeView.OnFeatureDoubleClick: event: " + str(event) + "\t" + str(event.x) +  "\t" + str(event.y))
        item = self.identify('item', event.x, event.y)
        print("MyTreeView.OnFeatureDoubleClick: ", self.item(item,"text"))

模拟您的示例,运行并产生以下输出:

[1,2,3,4,5,6,7].eachWithIndex { num, idx ->  
  int a = 2
  int b = 3
  println "${a + b} ${idx}: ${num}"
}

您不需要第二级花括号。同样,在您的代码中,您将~> groovy solution.groovy 5 0: 1 5 1: 2 5 2: 3 5 3: 4 5 4: 5 5 5: 6 5 6: 7 ~> 拼写为int,不需要在行尾使用分号,而且一般来说,groovy string interpolation比使用{{ 1}}。