Can an implementation of an enumeration that is a function be expressed using lambda?

Suppose I want to create a set of related functions and want to group them into an enumeration.

I can code, 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 not compiling):

enum CaseLambda implements Function<Object, String> {
    UPPER (o -> o.toString().toUpperCase()),
    LOWER (o -> o.toString().toLowerCase())
}

I tried several options for brackets, etc., but nothing compiles.

Is there any syntax that allows you to declare an implementation of an enum instance as lambda?

+4
source share
1 answer

No, the enumconstant syntax does not allow this. If you declare a constant with the body, this is the body classbody.

yshavit . Function.

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);
    }
}
+12

All Articles