Sobes.tech
Junior — Middle

Can you list and describe the constructors available for Sealed Class?

sobes.tech AI

Answer from AI

A Sealed Class in Kotlin is a class that restricts inheritance: all subclasses must be declared in the same file.

Regarding constructors for sealed classes:

  • The sealed class itself can have constructors, like a regular class.
  • Subclasses of the sealed class can have their own constructors.
  • Usually, the sealed class is declared as abstract, and its constructor can be protected or public.

Example:

sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val error: Throwable) : Result()
}

Here, the sealed class Result does not have an explicit constructor, but the subclasses Success and Error have their own constructors with parameters.

Thus, the sealed class itself can have constructors, but the constructors of its subclasses, which define specific variants, are often more important.