Difference Between Sealed Class and Enum Class in Kotlin

1. Introduction

In Kotlin, sealed classes and enums (short for enumerations) are ways to represent restricted class hierarchies. A sealed class is a type of class that restricts which classes can inherit from it. They are used to represent restricted class hierarchies where an object can only be of one of the given types. An enum, on the other hand, is a special type that represents a group of constants (unchangeable variables).

2. Key Points

1. Flexibility: Sealed classes are more flexible than enums as they can have multiple instances with different states.

2. Inheritance: Sealed classes can be inherited by other classes, enums cannot.

3. Type of Usage: Enums are ideal for simple fixed sets of values, and sealed classes are better for complex states with varied data.

4. Storage: Enums can store properties, but all instances of an enum constant have the same property values. Sealed classes can have different properties for each instance.

3. Differences

Characteristic Sealed Class Enum
Flexibility Highly flexible with different states Fixed set of constants
Inheritance Can be inherited Cannot be inherited
Type of Usage Complex states with varied data Simple fixed sets of values
Storage Different properties for each instance Same property values for all instances

4. Example

// Example of a Sealed Class
sealed class Result {
    data class Success(val message: String) : Result()
    data class Error(val error: Throwable) : Result()
}

// Example of an Enum
enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

Output:

Sealed Class Output:
Represents different types of results, each with its own state.
Enum Output:
Represents a fixed set of directions.

Explanation:

1. Result is a sealed class with different subclasses representing different types of results, allowing for rich state representation.

2. Direction is an enum that represents four fixed directions. Each direction is a single instance and cannot store different data per instance.

5. When to use?

- Use sealed classes when you need to represent complex states with rich information and behavior.

- Use enums when you need to define a fixed set of constants, like days of the week, states in a state machine, etc., and don't need to store varied information within each constant.

Comments