kotlin
  1. kotlin-sealed-class

Kotlin Sealed Class

In Kotlin, a sealed class is a class that is restricted to a fixed set of subtypes. It means that all subclasses of a sealed class must be defined within the same file where the sealed class is declared. This concept is similar to an enum in Java.

Syntax

The syntax for defining a sealed class in Kotlin is as follows:

sealed class MyClass {
    // Define subclasses of MyClass here
}

Example

The following example demonstrates the use of a sealed class in Kotlin:

sealed class Animal {
    class Dog(val name: String) : Animal()
    class Cat(val name: String) : Animal()
    class Bird(val name: String) : Animal()
}

fun getToken(animal: Animal): String {
    return when (animal) {
        is Animal.Dog -> "Dog Token"
        is Animal.Cat -> "Cat Token"
        is Animal.Bird -> "Bird Token"
    }
}

fun main() {
    val dog = Animal.Dog("Buddy")
    val cat = Animal.Cat("Fluffy")
    val bird = Animal.Bird("Tweety")

    println(getToken(dog))
    println(getToken(cat))
    println(getToken(bird))
}

Output

The output of the above example will be:

Dog Token
Cat Token
Bird Token

Explanation

In the above example, we define a sealed class Animal with three subclasses (Dog, Cat, and Bird). The getToken function takes an Animal object as a parameter and returns a token based on the type of the animal.

In the main function, we create instances of each subclass and pass them to the getToken function to get the tokens.

Since a sealed class is restricted to a fixed set of subtypes, the when-expression used in the getToken function must include a branch for every possible subtype of the sealed class. This makes it easier to handle all possible cases and avoid unexpected behaviors.

Use

Sealed classes are useful when you want to represent a restricted type hierarchy, where all possible subtypes are known upfront. They are particularly useful for representing state machines, where you want to restrict the possible states.

Using sealed classes in Kotlin allows you to write cleaner and more concise code, making it easier to reason about and maintain your codebase.

Important Points

  • A sealed class must have at least one subclass defined within the same file.
  • All subclasses of a sealed class must be declared within the same file where the sealed class is declared.
  • A sealed class cannot be instantiated directly (i.e. using Animal()).
  • Sealed classes are commonly used with when-expressions to handle all possible cases.

Summary

In this tutorial, we discussed the concept of sealed classes in Kotlin, their syntax, example usage, output, explanation, use, important points, and summary of the sealed class concept. We also explained why sealed classes are important and how they can help write cleaner and more concise code.

Published on: