A. Mashreghi A. Mashreghi - 1 year ago 50
Swift Question

Can I have function types in Java's Enum like Swift?

Is it possible to write an equivalent code in Java for the following swift code? In fact, I want to know if it's possible to have a case of functions inside Java's enum (X, Y in MyEnum)

enum MyEnum{
case X((Int) -> String)
case Y((Double) -> Int)

Answer Source

It is possible (technically), but it might not be that useful, as creating a simple class, that consumes a Function instance.

As you might already know, in Java, the enums represent one or more constants of the same type, which could have their own properties - this include java.util.Function instances. However, these Function instances cannot be passed dynamically at Runtime, but should be rather set at compile time, so that the constant is created.

Of course, you could make each enum constant have a different typed Function, by just creating the enum's constructor Generic:

enum MyEnum {
    X((String x) -> "Hello"), Y((Double d) -> 1);

    Function<?, ?> function;

    MyEnum(Function<?, ?> function) {
        this.function = function;    

This, however, is not quite useful (although it compiles just fine). The Function in X doesn't use it's String parameter and returns a fixed value. So does the one in Y.

I'd rather introduce two separate instances of the same class:

class Instance<T, U> {

    private Function<T, U> function;

    public Instance(Function<T, U> function) {
         this.function = function;

This will allow you to dynamically pass a Function instance, instead of setting it at compile-time.