Grails Cookbook - A collection of tutorials and examples

Convert String to Enum in Groovy

When programming in Grails, sometimes we get a String value that we wish to transform to an Enum. For example, when usually get String value from data passed from form or url parameters. Since Groovy 1.7.6, it is now easy to transform a String into a Enum value. Below are some examples:
enum SomeFoodEnum {
	APPLE(0), BANANA(1), CARROT(2)
	SomeFoodEnum(int value) {
		this.value = value
	}
	private final int value
	int getValue() {
		value
	}
}
String someString = 'BANANA'
SomeFoodEnum convertedEnumValue = someString as SomeFoodEnum
println convertedEnumValue
println convertedEnumValue.value
We can use the as keyword to convert a String to an Enum. The expected output of the code above is:
BANANA
1
From experimenting, it seems the as keyword is optional. We can directly use type coersion. Here is a revised example:
enum SomeFoodEnum {
	APPLE(0), BANANA(1), CARROT(2)
	SomeFoodEnum(int value) {
		this.value = value
	}
	private final int value
	int getValue() {
		value
	}
}
String someString = 'CARROT'
SomeFoodEnum convertedEnumValue = someString
println convertedEnumValue
println convertedEnumValue.value
Notice that we assigned the String value to an Enum variable straight, without the as keyword. And the code will still work. Here is the output:
CARROT
2