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" изглежда като метод, но се използва на "file" като затваряне. Затварянето е един от параметрите на "parseCSV" и най-объркващото - вътре в този метод има само closure(lineCount,field) без никаква вътрешна функционалност.

Как работи точно със затварянето на file.parseCSV и use(CSVParser.class)?


person Daniel    schedule 27.05.2013    source източник


Отговори (1)


Това е 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

person Will    schedule 27.05.2013