问题
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