I am converting Temperatures between Celsius, Farenheit, and <REDACTED>. I have a class…
- User
I am converting Temperatures between Celsius, Farenheit, and . I have a class Temperature that looks like this:
interface Temperature { Logger log = LoggerFactory.getLogger(Temperature.class);
codedouble value(); TemperatureUnits units(); record Measurement(double value, TemperatureUnits units) implements Temperature { @Override public Measurement convertTo(TemperatureUnits destinationUnits) { log.info("looking at destination units: " + destinationUnits); switch (destinationUnits) { case Farenheit -> { log.info("insider Farenheit block"); switch (units()) { case Celsius -> { return new Measurement(value() * 1.8 + 32, Farenheit); } case <REDACTED> -> { return new Temperature.Measurement((value() - 273.15) * 1.8 + 32, Farenheit); } default -> { return new Temperature.Measurement(value, units); }// } else if (units.equals(TemperatureUnits.Kelvin)) { // return new Temperature.Measurement(value() + 273.15, TemperatureUnits.Kelvin); // } } } case Celsius -> { switch (units()) { case Farenheit -> { return new Measurement((value() -32), Farenheit); } } } } return new Temperature.Measurement(value, units); } }
codeMeasurement convertTo(TemperatureUnits destinationUnits);}
- Assistant
- User
I am using Java 20 and want to use Pattern Matching so I don't have to do nested switch statements, so I was going to introduce a Tuple Record type and match on each combo, e.g. Tuple(Celsius, Farenheit)?
- Assistant
- User
If we did this code in Scala 3, we could do matches like:
case(Celsius, Farenheit) -> {}
No?
- Assistant
- User
Back on the Java version, if we changed the Units into a Sealed Interface, we could probably achieve pattern matching like we have in Scala, or closer, no?
- Assistant