Skip to content

Commit da1810e

Browse files
committed
feat: WeatherCode.from static method
Extracted from the serializer to ease parsing process from doubles. Also parsable from `Int`s and `Double`s to reduce final code clutter.
1 parent 68174ec commit da1810e

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

lib/src/main/kotlin/com/openmeteo/api/common/weather/WeatherCode.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,11 @@ enum class WeatherCode(val code: Short, val message: String) {
3838
THUNDERSTORM_HEAVY_HAIL(99, "Thunderstorm with heavy hail");
3939

4040
override fun toString(): String = message
41+
42+
companion object {
43+
fun from(code: Short) = values()
44+
.firstOrNull { it.code == code } ?: UNKNOWN
45+
fun from(code: Int) = from(code.toShort())
46+
fun from(code: Double) = from(code.toInt())
47+
}
4148
}

lib/src/main/kotlin/com/openmeteo/api/common/weather/WeatherCodeSerializer.kt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ object WeatherCodeSerializer : KSerializer<WeatherCode> {
1717
override fun serialize(encoder: Encoder, value: WeatherCode) = encoder.encodeShort(value.code)
1818
override fun deserialize(decoder: Decoder): WeatherCode {
1919
val code = decoder.decodeFloat().toInt().toShort()
20-
return WeatherCode.values()
21-
.firstOrNull { it.code == code } ?: WeatherCode.UNKNOWN
20+
return WeatherCode.from(code)
2221
}
2322
}

0 commit comments

Comments
 (0)