如何在Kotlin枚举中保留类型?附像素枚举场景示例
解决方案:保留Pixel枚举类型并对接Image的Color API
这问题挺常见的——想把枚举的类型安全和现有Image的Color API结合起来,对吧?我们可以通过给枚举添加转换逻辑,再扩展Image的操作方法来实现,全程保留Pixel的枚举类型,不用直接裸写Color。
1. 优化Pixel枚举类,添加Color转Pixel的映射
首先给你的Pixel枚举加一个伴生对象方法,用来从Image返回的Color反向查找对应的枚举值,这样就能把Color转回Pixel类型:
enum class Pixel(val state: Color) { ON(Color(200, 200, 200)), OFF(Color(50, 50, 50)); companion object { // 根据Color获取对应的Pixel,返回null表示颜色不匹配 fun fromColor(color: Color): Pixel? { return entries.find { it.state == color } } // 如果想强制颜色必须是枚举内的,找不到就抛异常 fun fromColorStrict(color: Color): Pixel { return entries.find { it.state == color } ?: throw IllegalArgumentException("Color $color doesn't match any Pixel state") } } }
2. 扩展自定义Image类,支持直接操作Pixel类型
因为你的img[x,y]只认Color,我们可以给Image写扩展函数,重载get和set运算符,让它直接支持Pixel类型:
// 扩展Image,让get操作返回Pixel? operator fun Image.get(x: Int, y: Int): Pixel? { val color = this.get(x, y) // 调用原Image的get方法 return Pixel.fromColor(color) } // 扩展Image,让set操作接受Pixel类型 operator fun Image.set(x: Int, y: Int, pixel: Pixel) { this.set(x, y, pixel.state) // 调用原Image的set方法,传入枚举对应的Color }
3. 使用示例:全程用Pixel类型操作
现在你就可以完全用Pixel枚举来和Image交互,不用碰Color了:
设置像素
// 直接用Pixel枚举设置,类型安全,不会传入非法Color img[15, 30] = Pixel.ON img[40, 25] = Pixel.OFF
获取像素并处理状态
val pixel = img[15, 30] when(pixel) { Pixel.ON -> println("这个像素是浅灰色(开启状态)") Pixel.OFF -> println("这个像素是深灰色(关闭状态)") null -> println("找到未知颜色的像素,不在枚举定义内") } // 如果用strict版本的转换,直接拿到非空Pixel val strictPixel = Pixel.fromColorStrict(img[40, 25]) if (strictPixel == Pixel.OFF) { // 处理关闭状态逻辑 }
这样做的好处是全程保留了枚举的类型安全——你只能用预定义的ON/OFF状态操作像素,避免了传入任意Color的风险,同时完美对接了现有Image的API。
内容的提问来源于stack exchange,提问作者Rares Dima
相关产品推荐
相关产品推荐

