BBC James Shephard Sep 11, 2017

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

Critical Insight

Sealed classes combined with when() syntax offer a cleaner, safer alternative to callbacks by decoupling thread marshalling from result handling at compile time.

The article reveals why making assumptions about callback contexts in your APIs might be limiting your architecture more than you realize.

About This Article

Problem

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.

Solution

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.

Impact

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.