-
Notifications
You must be signed in to change notification settings - Fork 22
Enum compared with sealed classes
Devrath edited this page Dec 22, 2023
·
2 revisions
Enum |
SealedClasses |
---|---|
Enum classes represent a concrete set of values | sealed classes represent a concrete set of classes |
They are perfect to represent a constant set of possible values | They are great to define a set of events or messages that might occur |
The advantage of enum classes is that they can be serialized and deserialized out of the box. They have methods valueOf , values which are easy to iterate |
The advantage of sealed classes is that they can hold instance-specific data |
- Enum: An enum class in Kotlin is a special kind of sealed class that represents a set of distinct values. Each value is a singleton instance of the enum class. Enum instances are limited to the defined values within the enum class.
- Sealed Class: A sealed class can have multiple instances, each representing a different subtype. Sealed classes allow for a limited set of subclasses defined within the same file or module.
// Enum example
enum class Color {
RED, GREEN, BLUE
}
// Sealed class example
sealed class Result
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
- Enum: You cannot extend an enum class in Kotlin. Enum classes are final by default.
- Sealed Class: Sealed classes can be extended, but the subclasses must be defined in the same file or module where the sealed class is declared.
// Enum class (cannot be extended)
enum class Color { RED, GREEN, BLUE }
// Sealed class (can be extended)
sealed class Result
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
- Enum: You can define properties and methods for each enum value, but they are shared among all instances.
- Sealed Class: Each subclass of a sealed class can have its own properties and methods. Sealed classes are more flexible in terms of allowing different behavior for each subtype.
// Enum with properties and methods
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF);
fun toHexString(): String {
return Integer.toHexString(rgb)
}
}
// Sealed class with properties and methods
sealed class Result {
data class Success(val data: String) : Result() {
fun printData() {
println(data)
}
}
data class Error(val message: String) : Result() {
fun printError() {
println(message)
}
}
}