使用关联类型时,密封类vs枚举 [英] sealed class vs enum when using associated type

查看:136
本文介绍了使用关联类型时,密封类vs枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于Int创建一个颜色对象.我可以使用sealed classenum达到相同的结果,并且想知道一个是否比另一个更好.

I'd like to create a color object based on an Int. I can achieve the same result using sealed class and enum and was wondering if one is better than the other.

使用sealed class:

sealed class SealedColor(val value: Int) {
    class Red : SealedColor(0)
    class Green : SealedColor(1)
    class Blue : SealedColor(2)

    companion object {
        val map = hashMapOf(
            0 to Red(),
            1 to Green(),
            2 to Blue()
        )
    }
}

val sealedColor: SealedColor = SealedColor.map[0]!!
when (sealedColor) {
                is SealedColor.Red -> print("Red value ${sealedColor.value}")
                is SealedColor.Green -> print("Green value ${sealedColor.value}")
                is SealedColor.Blue -> print("Blue value ${sealedColor.value}")
            }

使用enum:

enum class EnumColor(val value: Int) {
    Red(0),
    Green(1),
    Blue(2);

    companion object {
        fun valueOf(value: Int): EnumColor {
            return EnumColor
                .values()
                .firstOrNull { it.value == value }
                    ?: throw NotFoundException("Could not find EnumColor with value: $value")
        }
    }
}

val enumColor: EnumColor = EnumColor.valueOf(0)
when (enumColor) {
            EnumColor.Red -> print("Red value ${enumColor.value}")
            EnumColor.Green -> print("Green value ${enumColor.value}")
            EnumColor.Blue -> print("Blue value ${enumColor.value}")
        }

它们的性能是否相等?有没有更好的Kotlin方法来达到相同的结果?

Are they equivalent in term of performance? Is there a better kotlin way to achieve the same result?

推荐答案

sealed类被称为枚举类的扩展" .它们可以存在于包含状态的多个实例中.由于您不需要多次实例化这些值,并且它们也不会提供特殊的行为,因此枚举应该恰好适合该用例,并且在此处更易于理解.

sealed classes are said to be "an extension of enum classes". They can exist in multiple instances that contain state. Since you don't need the values to be instantiated multiple times and they don't provide special behaviour, enums should just be right for the use case and easier to understand here.

在您的示例中根本不需要sealed.

There's simply no need for sealed in your example.

这篇关于使用关联类型时,密封类vs枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆