Start Coding

Topics

Kotlin Sealed Classes

Sealed classes in Kotlin provide a powerful way to represent restricted class hierarchies. They are particularly useful when dealing with a finite set of subclasses.

What are Sealed Classes?

A sealed class is a class that restricts the possibility of inheritance. All direct subclasses of a sealed class must be declared in the same file as the sealed class itself. This feature ensures that the compiler knows all possible subclasses at compile-time.

Syntax and Usage

To declare a sealed class, use the sealed keyword before the class keyword:

sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()
object Loading : Result()

In this example, Result is a sealed class with three subclasses: Success, Error, and Loading.

Benefits of Sealed Classes

  • Exhaustive when expressions
  • Type-safe handling of different cases
  • Improved code organization
  • Better representation of domain models

Common Use Cases

Sealed classes are often used in scenarios where you need to represent a limited set of possibilities, such as:

  • API responses (success, error, loading)
  • State management in UI components
  • Representing different shapes in a graphics system

Example: Using Sealed Classes with when Expression

Here's an example demonstrating how to use a sealed class with a when expression:

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

val successResult = Success("Data loaded")
handleResult(successResult) // Output: Success: Data loaded

val errorResult = Error("Network error")
handleResult(errorResult) // Output: Error: Network error

handleResult(Loading) // Output: Loading...

In this example, the when expression is exhaustive without needing an else branch, as the compiler knows all possible subclasses of Result.

Best Practices

  • Use sealed classes for representing finite sets of related types
  • Keep sealed class hierarchies simple and focused
  • Combine sealed classes with data classes for immutable value objects
  • Utilize sealed classes in pattern matching with when expressions

Conclusion

Sealed classes in Kotlin offer a robust way to model restricted hierarchies. They provide type safety, exhaustive checking, and improved code organization. By leveraging sealed classes, you can create more expressive and maintainable code, especially when dealing with finite sets of related types.