2013-05-27 34 views
1

有没有人可以解释我,这段代码是如何工作的?Groovy - 关闭 - 读取CSV

class CSVParser { 
    static def parseCSV(file,closure) { 
     def lineCount = 0 
     file.eachLine() { line -> 
      def field = line.tokenize(",") 
      lineCount++ 
      closure(lineCount,field) 
     } 
    } 
} 

use(CSVParser.class) { 
    File file = new File("test.csv") 
    file.parseCSV { index,field -> 
     println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}" 
    } 
} 

链接:http://groovy-almanac.org/csv-parser-with-groovy-categories/

“parseCSV” 看起来就像一个方法,但在 “文件” 的封闭使用。 Closure是“parseCSV”参数之一,最容易混淆 - 在这个方法中,只有closure(lineCount,field)没有任何内部功能。

它如何与file.parseCSVuse(CSVParser.class)上的关闭一起工作?

回答

2

这是一个Category;简单地说,他们使一个方法从一个类“成为”第一个参数对象的方法。作为参数传递的闭包不会添加到示例中;它可能是一个字符串或其他任何东西:

class Category { 
    // the method "up()" will be added to the String class 
    static String up(String str) { 
    str.toUpperCase() 
    } 

    // the method "mult(Integer)" will be added to the String class 
    static String mult(String str, Integer times) { 
    str * times 
    } 

    // the method "conditionalUpper(Closure)" will be added to the String class 
    static String conditionalUpper(String str, Closure condition) { 
    String ret = "" 
    for (int i = 0; i < str.size(); i++) { 
     char c = str[i] 
     ret += condition(i) ? c.toUpperCase() : c 
    } 
    ret 
    } 
} 

use (Category) { 
    assert "aaa".up() == "AAA" 
    assert "aaa".mult(4) == "aaaaaaaaaaaa" 
    assert "aaaaaa".conditionalUpper({ Integer i -> i % 2 != 0}) == "aAaAaA" 
} 

而且那是多么Groovy Extensions工作