---
title: "groovy对象闭包迭代"
author: "prowl"
date: "2009-12-29T17:57:58Z"
tags: []
categories: ["编程语言"]
slug: "groovy"
draft: false
lastmod: "2009-12-29T17:57:58Z"
id: 559330
url: "https://prowl.iteye.com/blog/559330"
---

看了2天groovy，感觉真的很nice，一个闭包迭代的例子。


```groovy

class ClosureSample
{
    def array
    
    def foreach(func)
    {
        array.size().times
        {
            func(array[it])
        }
    }
}

def cs=new ClosureSample(array:[1,2,3,4])

cs.foreach({println it})

```


函数名不能用each，否则会print出对象的地址，这点不明白是为什么。

闭包给人感觉像是java的Template Pattern，不过更灵活。