With all the fuss about the new closure to SAM type coercion in Groovy 2.2 [0] I was remembered of another neat coercion feature some of my work colleagues seemed not to know about.
Strings and Enumerations in Groovy
Since Groovy 1.7.6 the language supports a feature called "String to enum coercion" [1]. Well, that might say it all, but let's have a look what this means with a small code example:
Let's assume we have an enum type called Day, resembling an enumeration of all the week days. If we wanted to get the enumeration value for a given string, we would have to do something like that in Java code:
Daysunday=Day.valueOf("Sunday");
Groovy comes with a nicer way of coercing a string to an arbitrary enumeration using the as operator:
Daysunday="Sunday"asDay
The as operator can actually be left aside in this case which leaves us with:
Daysunday="Sunday"
Note that this feature not only works for plain java.lang.String instances but also for GString instances:
Daysunday="${ ['Sun', 'day'].join()}"
The coercion also works in the opposite direction, if we wanted a string from our enumeration value we can simply do:
Stringday=Day.Sunday
Conclusion
The String to enum coercion is especially useful if your are dealing with strings coming for example from HTTP request instances and you need a fast way to retrieve an enumeration value.