Last time, I set out to build a Result<T, E> type in Kotlin, and discovered some awkwardness around parameterizing the types of the variants. This issue, I realize I totally forgot about covariance, which significantly mitigates the awkwardness.
A Result<T, E> Type in Kotlin
edit: I made a mistake in this article! See Covariance in a Result<T, E> type in Kotlin for corrections.
Kotlin provides a mechanism for sum types in the form of sealed classes. It works by closing the class for extension outside the immediate context, allowing the compiler to know every possible subtype and perform the exhaustive checking expected of the variants of a sum type. However, some typical sum type use cases are a touch awkward with this approach. Let's explore by trying to write a Result<T, E> type in Kotlin using a sealed class.