Can I have function types in Java Enum like Swift?

Is it possible to write equivalent code in Java for the following quick code? Actually, I want to know if it is possible to have a case of functions inside a Java enumeration (X, Y in MyEnum)

enum MyEnum{
    case X((Int) -> String)
    case Y((Double) -> Int)
}
+4
source share
3 answers

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

, Java , - java.util.Function. Function , , .

, , Function, enum Generic:

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

    Function<?, ?> function;

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

, , ( ). Function X String . Y.

:

class Instance<T, U> {

    private Function<T, U> function;

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

Function, .

+2

, ; , , , . .

, "enum" , :

final class MyHeterogeneousEnum {
  private MyHeterogeneousEnum() {}  // Not instantiable.

  static final Function<Integer, String> X = ...;
  static final Function<Double, Integer> Y = ...;
}

:

String s = MyHeterogeneousEnum.X.apply(123);
Integer i = MyHeterogeneousEnum.Y.apply(999.0);

, , name() values(), . - values() , :

static Iterable<Function<?, ?>> values() {
  return Collections.unmodifiableList(Arrays.asList(X, Y));
}

, a Function : - ( null); values() .

+3

, , , java , ... (, TimeUnit.class)

- :

interface IFunction {
    double getY(double x);
}


enum Function implements IFunction {
    LINE {
    @Override
    public double getY(double x) {
        return x;
    }
    },
    SINE {
    @Override
    public double getY(double x) {
        return Math.sin(x);
    }
    }
}

public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
        System.out.println(Function.LINE.getY(i));
        System.out.println(Function.SINE.getY(i));
    }
}
+1

Source: https://habr.com/ru/post/1653286/


All Articles