I am wondering if there is an option to return a generic type from a Java 12 switch expression.
The basic code can look like that:
boolean result = switch(ternaryBool) {
case TRUE -> true;
case FALSE -> false;
default -> throw new IllegalArgumentException("Seriously?!");
};
Is there anything against doing it this way?
T result = switch(ternaryBool) {
case TRUE -> BooleanUtils.toBoolean('true');
case FALSE -> new Integer(0);
default -> throw new IllegalArgumentException("Seriously?!");
};
EDIT:
Maybe better example from my case: I need to have few classes which are representing primitive & complex data structures. I have also factory method which is creating this DataPointValue
based on an enum from other system and unknown value (let's forget about casting exceptions):
public static <T> IDataPointValue create(T value, DATA_TYPE dataType) throws Exception {
try {
switch (dataType) {
case BOOL:
return new BoolDataPointValue((Boolean) value);
case INT:
return new IntDataPointValue((Integer) value);
case WORD:
return new IntDataPointValue((Integer) value);
case STRING:
return new StringDataPointValue((String) value);
case REAL:
case FLOAT:
return new RealDataPointValue((Float) value);
case DINT:
return new DIntDataPointValue((Integer) value);
case DWORD:
return new DWordDataPointValue((Integer) value);
default:
throw new Exception("Data Type not implemented: " + dataType);
}
} catch (ClassCastException e){
throw new Exception("Could not create DPV in terms of Type incompability");
}
}
Is there any profit to move this code and use switch expression from Java 12?