Google News
logo
Kotlin - Interview Questions
What are sealed classes in Kotlin?
In Kotlin, a sealed class is a special type of class that restricts the inheritance hierarchy of its subclasses. It allows you to define a closed set of subclasses that are known and limited in advance. Here are some key points about sealed classes:

1. Limited Subclass Hierarchy :
   * A sealed class can have a predefined and limited number of subclasses.
   * All the subclasses of a sealed class must be declared within the same Kotlin file where the sealed class is declared.
   * This ensures that the subclasses of a sealed class are known and restricted within a specific scope.

2. Restricted Inheritance :
   * The subclasses of a sealed class must be declared as nested classes or subclasses within the same file.
   * Sealed classes cannot be instantiated directly.
   * This restricts the inheritance hierarchy of the sealed class to only those subclasses defined within the same file.

3. Useful for Representing Restricted Types :
   * Sealed classes are commonly used to represent restricted types or algebraic data types, where the value can only be one of the defined subclasses.
   * Each subclass can represent a specific case or variation of the sealed class.
4. Exhaustive when Statements :
   * Sealed classes work well with when expressions or statements in Kotlin.
   * The compiler can perform exhaustive checks in when statements, ensuring that all possible subclasses are handled, eliminating the need for an else branch.

Here's an example to illustrate the usage of sealed classes :
sealed class Result
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
object Loading : Result()

fun processResult(result: Result) {
    when (result) {
        is Success -> println(result.data)
        is Error -> println(result.message)
        Loading -> println("Loading")
    }
}​

In the example, `Result` is a sealed class with three subclasses: `Success`, `Error`, and `Loading`. These subclasses represent different cases or variations of the `Result` type. The sealed class ensures that these subclasses are limited and known in advance. The `processResult` function uses a when expression to handle each possible case of the sealed class.

Sealed classes provide a powerful mechanism for modeling restricted types and representing a closed set of subclasses. They improve code safety by limiting the possibilities and ensuring exhaustive checks in when statements.
Advertisement