Creating when construct in Groovy using closures


/ Published in: Groovy
Save to your folder(s)

A nice example of utilizing Groovy closures in order to create a when statement in Groovy (http://www.transentia.com.au/flatpress/?x=entry:entry090311-222726).


Copy this code and paste it in your HTML
  1. def car = "Patriot"
  2.  
  3. def manufacturer = match(car) {
  4. when "Focus", "Ford"
  5. when "Navigator", "Lincoln"
  6. when "Camry", "Toyota"
  7. when "Civic", "Honda"
  8. when "Patriot", "Jeep"
  9. when "Jetta", "VW"
  10. when "Ceyene", "Porsche"
  11. when "Outback", "Subaru"
  12. when "520i", "BMW"
  13. when "Tundra", "Nissan"
  14. otherwise "Unknown"
  15. }
  16.  
  17. println "The $car is made by $manufacturer"
  18.  
  19. def match(obj, closure) {
  20. closure.subject = obj
  21. closure.when = { value, result ->
  22. if (value == subject)
  23. throw new MatchResultException(result: result)
  24. }
  25. closure.otherwise = { return it }
  26. closure.resolveStrategy = Closure.DELEGATE_FIRST
  27. try {
  28. closure()
  29. closure.otherwise()
  30. } catch (MatchResultException r) {
  31. r.result
  32. }
  33. }
  34.  
  35. class MatchResultException extends RuntimeException {
  36. def result
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.