Groovy Quick Tip: String to Enum Coercion

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:
 

enum Day {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

 
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:
 

Day sunday = Day.valueOf("Sunday");

 
Groovy comes with a nicer way of coercing a string to an arbitrary enumeration using the as operator:
 
Day sunday = "Sunday" as Day
 
The as operator can actually be left aside in this case which leaves us with:
 
Day sunday = "Sunday"
 
Note that this feature not only works for plain java.lang.String instances but also for GString instances:
 
Day sunday = "${ ['Sun', 'day'].join()}"
 
The coercion also works in the opposite direction, if we wanted a string from our enumeration value we can simply do:
 
String day = 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.

[0] Groovy 2.2 Release Notes
[1] GROOVY-4501: String to enum coercion