sealed class vs enum when using associated type

*爱你&永不变心* 提交于 2020-04-29 08:58:22

问题


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.

Using 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}")
            }

Using 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}")
        }

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/49169086/sealed-class-vs-enum-when-using-associated-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!