如何在 kotlin 数据中使用枚举 class

How do I use an enum within a kotlin data class

我有这个模型

data class HourlyModel(
    val time: String,
    @DrawableRes val image: Int,
    val temp: Double
)

我意识到服务器会向我提供天气代码,这些代码会转换为将要显示的图标。我认为如果我将 @DrawableRes 放入一个枚举中,可能会更好,因为我有一个用于今日天气和每周天气预报的模型。

所有 3 个模型将使用相同的天气代码。 我是 Kotlin 的新手,但我想如果我有一个枚举 class,我应该能够以某种方式在每个模型中使用它

enum class WeatherTypes (
    val weatherCode: Int,
    @DrawableRes val drawable: Int
) {
    SUNNY(0, R.drawable.sunny_t),
    RAIN(1,R.drawable.rain_t);
    
    companion object {
        fun weatherToImage(weatherCode: Int) = when(weatherCode) {
            0 -> SUNNY
            1 -> RAIN
            else -> SUNNY
        }
    }
}

有人可以帮助我并告诉我应该如何处理我的模型以使用此枚举 class 来替换 @DrawableRes 吗?如果我不能,那么对我来说最好的选择是什么?

我假设您对不同的层有不同的模型。假设您有一个数据 class 用于从服务器接收的数据。

data class HourlyDto(
    val time: String,
    val weatherCode: Int,
    val temp: Double,
)

您的领域模型将是这样的:

data class HourlyModel(
    val time: String,
    val weatherType: WeatherType,
    val temp: Double,
)

我重构了你的枚举 class:

enum class WeatherType(
    @DrawableRes val imageResId: Int,
) {
    SUNNY(R.drawable.sunny_t),
    RAIN(R.drawable.rain_t);

    companion object {
        fun from(weatherCode: Int): WeatherType {
            return WeatherType.values()[weatherCode]
        }
    }
}

现在,您可以将远程模型映射到域模型。让我们为此创建一个扩展函数(作为示例。您可能会以另一种方式进行)

fun HourlyDto.mapToModel(): HourlyModel {
    return HourlyModel(
        time,
        WeatherType.from(weatherCode),
        temp
    )
}

最后,您可以像这样使用您的可绘制对象 resource-id:

val hourlyWeather: HourlyModel = ...
hourlyWeather.weatherType.imageResId

注意: 这回答了如何在模型中使用枚举的问题 class,但我想要解决这个特定问题,您可以使用原始模型( with drawable resource-id) 然后创建一个辅助函数,它接受 weathercode 和 returns 可绘制对象 resource-id 并在需要的地方重用它。