Kotlin: An Exploration of Sealed Classes
Article Summary
James Shephard from BBC explores how Kotlin's sealed classes can fundamentally reshape your Android architecture. What if callbacks aren't the answer to async operations?
A BBC engineer dives deep into Kotlin sealed classes, comparing them to Java's traditional approaches for handling different data types and async operations. The article challenges common patterns like receiver callbacks and explores how a simple language feature can trigger architectural rethinking.
Key Takeaways
- Sealed classes provide compile time safety for handling different data types
- Smart casting eliminates explicit casts and complicated contracts with calling code
- Separates async concerns from result handling using standard concurrency frameworks
- Blocking interfaces adapt easier to non blocking than callbacks adapt to blocking
- Similar to Swift enums with associated values for type safe state
Sealed classes combined with when() syntax offer a cleaner, safer alternative to callbacks by decoupling thread marshalling from result handling at compile time.
About This Article
BBC's Android teams had trouble with unsafe data access patterns in deserialized message objects. Attributes were only valid in certain situations, but there was no way to enforce this at compile time. This meant they had to rely on runtime documentation and exception handling.
James Shephard used Kotlin's sealed classes and when() syntax to build type-safe message handlers. The objects transparently cast themselves and only expose the attributes relevant to each message subtype. This removed the need for explicit casting and runtime validation.
The new architecture separated asynchronous thread marshalling from result handling by using standard Java concurrency frameworks instead of callbacks. UI presenter components that handle long-running background tasks now have cleaner separation of concerns.