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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With