groovy.groovy 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //http://groovy.codehaus.org/Martin+Fowler%27s+closure+examples+in+Groovy
  2. class Employee {
  3. def name, salary
  4. boolean manager
  5. String toString() { return name }
  6. }
  7. def emps = [new Employee(name:'Guillaume', manager:true, salary:200),
  8. new Employee(name:'Graeme', manager:true, salary:200),
  9. new Employee(name:'Dierk', manager:false, salary:151),
  10. new Employee(name:'Bernd', manager:false, salary:50)]
  11. def managers(emps) {
  12. emps.findAll { e -> e.isManager() }
  13. }
  14. assert emps[0..1] == managers(emps) // [Guillaume, Graeme]
  15. def highPaid(emps) {
  16. threshold = 150
  17. emps.findAll { e -> e.salary > threshold }
  18. }
  19. assert emps[0..2] == highPaid(emps) // [Guillaume, Graeme, Dierk]
  20. def paidMore(amount) {
  21. { e -> e.salary > amount}
  22. }
  23. def highPaid = paidMore(150)
  24. assert highPaid(emps[0]) // true
  25. assert emps[0..2] == emps.findAll(highPaid)
  26. def filename = 'test.txt'
  27. new File(filename).withReader{ reader -> doSomethingWith(reader) }
  28. def readersText
  29. def doSomethingWith(reader) { readersText = reader.text }
  30. assert new File(filename).text == readersText