Sobes.tech
Junior — Middle

Milline on erinevus sealed classi ja enumi kasutamisel nende konstruktorite ja loomise võimaluste osas?

sobes.tech AI

Vastus AI-lt

In Kotlin (and Java), an enum represents a set of fixed constants. Each enum has a limited set of instances, defined within the declaration itself. Enum constructors are always private, and new instances cannot be created — only those declared.

A sealed class is an abstract class with a limited number of subclasses, declared in the same file. Unlike enum, a sealed class allows creating different types with different structures and states. The constructors of a sealed class can be open or closed, and new instances of subclasses can be created, not just fixed constants.

Example:

// Enum with private constructor and fixed instances
enum class Direction(val degrees: Int) {
    NORTH(0), EAST(90), SOUTH(180), WEST(270)
}

// Sealed class with different subclasses and constructors
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: Throwable) : Result()
}

val res: Result = Result.Success("OK")

Thus, an enum is limited to a fixed set of instances with a private constructor, while a sealed class is more flexible, allowing the creation of different subclasses with their own constructors and states.