Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java function signature accept single enum value

Tags:

java

I have a Java class with multiple "type" values, and a class which can take one of those types.

I'm trying to change the implementation of the constructor depending the Type enum using Java's type system, but can't find any information on how to do it.

public enum Type {
    A,
    B,
    C
}

public class Action {
    public Action(Type.A type, String value) {}
    public Action(Type.B type, Float value) {}
    public Action(Type.C type, String value) {}
}

Is something to this effect possible in Java? Like it is in Typescript for example.

like image 598
Bennett Hardwick Avatar asked May 26 '19 02:05

Bennett Hardwick


1 Answers

No, what you wrote will not compile.

You can have named factory methods + a private constructor to achieve a similar result:

public class Action {
  private Action(Type discriminator, String s, Float f) {...}
  public static ofA(String value) { return new Action(Type.A, value, null); }
  public static ofB(Float value)  { return new Action(Type.B, null, value); }
  public static ofC(String value) { return new Action(Type.C, value, null); }
}

The constructor will likely have a number of if / else branches. (Sorry, algebraic types and pattern matching are not yet available in Java.)

like image 196
9000 Avatar answered Oct 30 '22 16:10

9000