1

Is there anybody, who can explain me, how works this piece of code?

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]}"  
    }  
}  

The link: http://groovy-almanac.org/csv-parser-with-groovy-categories/

"parseCSV" looks as a method, but is used on "file" as closure. Closure is one of the "parseCSV" parameters and most confusingly - inside this method there is just closure(lineCount,field) without any inner functionality.

How does it work exactly with closure on file.parseCSV and use(CSVParser.class)?

4

1 回答 1

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的工作方式

于 2013-05-27T19:26:52.817 回答