Suppose I want to create a set of related functions and want to group them in an enum.
I can code, just for example:
enum Case implements Function<Object, String> {
UPPER {
public String apply(Object o) {
return o.toString().toUpperCase();
}
},
LOWER {
public String apply(Object o) {
return o.toString().toLowerCase();
}
}
}
I would like to be able to code this as a lambda, something like (but doesn't compile):
enum CaseLambda implements Function<Object, String> {
UPPER (o -> o.toString().toUpperCase()),
LOWER (o -> o.toString().toLowerCase())
}
I've tried a few variations of brackets etc, but nothing compiles.
Is there a syntax that allows the declaration of enum instance implementation as lambda?
No, the enum
constant syntax does not allow it. If you declare a constant with a body, that body is a classbody
.
yshavit's suggestion seems appropriate. Delegate to the Function
implementation.
enum Case implements Function<Object, String> {
UPPER (o -> o.toString().toUpperCase()),
LOWER (o -> o.toString().toLowerCase());
private final Function<Object, String> func;
private Case(Function<Object, String> func) {
this.func = func;
}
@Override
public String apply(Object t) {
return func.apply(t);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With