I'm trying to define the following anonymous Google Guava Function instance:
Function<E extends Enum<E>, String> ENUM_TO_STRING = new Function<E extends Enum<E>, String>() {
@Override
public String apply(E enumValue) {
String result = null;
if (enumValue != null) {
result = enumValue.toString();
}
return result;
}
};
The idea is a simple transform function instance with an apply method that calls toString on any enum value if not null, or returns null if the value is null.
Unfortunately, the compiler complains about the generic reference E extends Enum. I know that this expression can be used in non-anonymous contexts, e.g:
public static <E extends Enum<E>> String enumToString(E enumValue) {
String result = null;
if (enumValue != null) {
result = enumValue.toString();
}
return result;
}
The first, anonymous class definition is not OK. The second non-anonymous method definition is OK.
Is there anyway to define an anonymous class using Enums?
Thanks