Groovy Enums example

Based on Coins example here, I developed a enumeration for me to crawl the various tables in this page on Wiki.
What I found interesting was the synthesis of the values() property from value and wasn’t sure whether it would return the names or the values. Here’s an example to clarify how things work.

enum NANPCodeGroup {
  USA(3), Canada(4), Carribean(5), USPacific(6)
  NANPCodeGroup(int value) {this.value = value}
  private final int value
  public int value() {return value}
}
NANPCodeGroup.each{println "1: $it"}
NANPCodeGroup.each{println "2: ${it.value()}"}
println "3: ${NANPCodeGroup.values()}"
NANPCodeGroup.values().each{println "4: $it"}
println "5: ${NANPCodeGroup.USA.value()}"
println "6: ${NANPCodeGroup.USA}"
x = NANPCodeGroup.grep{it.value() == 3}[0]?:''
println "7: $x , ${x.class}"
1: USA
1: Canada
1: Carribean
1: USPacific
2: 3
2: 4
2: 5
2: 6
3: [USA, Canada, Carribean, USPacific]
4: USA
4: Canada
4: Carribean
4: USPacific
5: 3
6: USA
7: USA , class NANPCodeGroup
Advertisements

About this entry