【问题标题】:Groovy - closure - reading CSVGroovy - 闭包 - 读取 CSV
【发布时间】:2013-05-22 15:49:32
【问题描述】:

有没有人可以解释一下,这段代码是如何工作的?

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.parseCSVuse(CSVParser.class) 上的闭包究竟是如何工作的?

【问题讨论】:

    标签: parsing csv groovy closures


    【解决方案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 也是这样工作的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多