Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an implementation of an enum that is a Function be expressed using a lambda?

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?

like image 473
Bohemian Avatar asked Oct 31 '14 00:10

Bohemian


1 Answers

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);
    }
}
like image 94
Sotirios Delimanolis Avatar answered Sep 20 '22 18:09

Sotirios Delimanolis