Sling Academy
Home/Kotlin/What Are Sealed Classes in Kotlin?

What Are Sealed Classes in Kotlin?

Last updated: November 30, 2024

Sealed classes in Kotlin are a unique and powerful feature that help developers manage type hierarchies in a controlled way. In essence, sealed classes are used to represent restricted class hierarchies, where a value can have one of the types from a limited set, but no other types.

Why Use Sealed Classes?

Sealed classes are useful when you have a well-defined set of possible alternatives for a value and you want to limit the use of those alternatives to a specific part of your code. This is particularly handy in scenarios like when you're implementing states in a state machine or responses in networking code.

Defining Sealed Classes

To declare a sealed class in Kotlin, you use the sealed keyword. The direct subclasses of a sealed class must be declared in the same file but can be defined in separate modules. Here’s an example:

sealed class Operation {
    data class Add(val value: Int) : Operation()
    data class Subtract(val value: Int) : Operation()
    object Reset : Operation()
}

In this snippet, Operation is a sealed class with two data class subclasses, Add and Subtract, and one singleton object Reset. Each subclass is a valid alternative of operation that can be performed.

Benefits of Using Sealed Classes

Sealed classes offer several benefits:

  • Exhaustive 'when' expressions: When you use a sealed class in a when expression, the compiler checks if all possible cases are covered, which helps avoid runtime errors.
  • Enhanced readability: By highlighting relationships more declaratively, sealed classes make code easy to read and understand.
  • Enhanced safety: Since classes are confined to a specific set of instances, it’s easier to manage changes without breaking existing logic.

Using Sealed Classes in 'when' Expressions

Here is an example of how you can use sealed classes in a when expression:

fun process(operation: Operation) = when (operation) {
    is Operation.Add -> println("Adding ${operation.value}")
    is Operation.Subtract -> println("Subtracting ${operation.value}")
    Operation.Reset -> println("Reset operation")
}

In this code, the when statement is exhaustive and processes all possible operations defined in the Operation sealed class.

Conclusion

Sealed classes provide a structured and expressive way to handle limited set hierarchies, enhancing code safety, clarity, and maintainability. With their exhaustiveness checks on expressions, they contribute significantly to reliable software applications.

Next Article: Using Sealed Classes for Restricted Class Hierarchies in Kotlin

Previous Article: Using `copy` to Clone and Modify Data Class Objects in Kotlin

Series: Kotlin Object-Oriented Programming

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin