Introduction
The Temperature Converter converts between Celsius, Fahrenheit, and Kelvin. It demonstrates enum usage, switch expressions, static methods, and input validation in a practical context.
| From | To | Formula |
| Celsius | Fahrenheit | F = C × 9/5 + 32 |
| Celsius | Kelvin | K = C + 273.15 |
| Fahrenheit | Celsius | C = (F − 32) × 5/9 |
| Kelvin | Celsius | C = K − 273.15 |
Full Code
enum TempUnit { celsius, fahrenheit, kelvin }
class TemperatureConverter {
static double toCelsius(double value, TempUnit from) {
return switch (from) {
TempUnit.celsius => value,
TempUnit.fahrenheit => (value - 32) * 5 / 9,
TempUnit.kelvin => value - 273.15,
};
}
static double fromCelsius(double celsius, TempUnit to) {
return switch (to) {
TempUnit.celsius => celsius,
TempUnit.fahrenheit => celsius * 9 / 5 + 32,
TempUnit.kelvin => celsius + 273.15,
};
}
static double convert(double value, TempUnit from, TempUnit to) {
if (from == TempUnit.kelvin && value < 0) {
throw ArgumentError('Kelvin cannot be negative');
}
return fromCelsius(toCelsius(value, from), to);
}
static String symbol(TempUnit unit) => switch (unit) {
TempUnit.celsius => '°C',
TempUnit.fahrenheit => '°F',
TempUnit.kelvin => 'K',
};
}
void main() {
void show(double v, TempUnit from, TempUnit to) {
try {
var r = TemperatureConverter.convert(v, from, to);
print('$v$${TemperatureConverter.symbol(from)} = $${r.toStringAsFixed(2)}$${TemperatureConverter.symbol(to)}');
} on ArgumentError catch (e) { print('Error: $${e.message}'); }
}
show(100, TempUnit.celsius, TempUnit.fahrenheit); // 100°C = 212.00°F
show(32, TempUnit.fahrenheit, TempUnit.celsius); // 32°F = 0.00°C
show(300, TempUnit.kelvin, TempUnit.celsius); // 300K = 26.85°C
show(-10, TempUnit.kelvin, TempUnit.fahrenheit); // Error
}
Output:100.0°C = 212.00°F
32.0°F = 0.00°C
300.0K = 26.85°C
Error: Kelvin cannot be negative
🧠 Quiz
1. Why use enums for temperature units?
- A) Faster than strings
- B) Prevents invalid values at compile time ✅
- C) Shorter code
- D) Required by switch
Summary
The temperature converter uses enums for type-safe units and a two-step conversion (via Celsius) to handle all unit pairs with only two switch expressions. Input validation in the convert method catches physically impossible Kelvin values.