Junior — Middle
What are the advantages and disadvantages of using sealed class in different project files?
sobes.tech AI
Answer from AI
Sealed class in Kotlin restricts inheritance: all subclasses must be declared in the same file as the sealed class itself, or in some cases within the same module.
Advantages of using sealed class in one file:
- Compactness and clarity: all variants of subclasses are visible immediately, which facilitates understanding and maintenance.
- The compiler can check the completeness of when-expressions, as all subclasses are known.
Disadvantages:
- Restriction on code organization: all subclasses must be in one file, which can lead to a large and cumbersome file.
Using sealed class in different files:
- In Kotlin 1.5+, subclasses of a sealed class can be declared in the same module but in different files if the sealed class is declared as
sealed interfaceor withsealedand@JvmSealed.
Advantages:
- Better code organization, each subclass in a separate file.
Disadvantages:
- Loss of compactness, harder to see all variants of subclasses immediately.
- Possible difficulties with maintaining the completeness of when-expressions if the compiler does not see all subclasses.
The choice depends on the size of the project and organizational preferences.