Self-Referential Generics in Kotlin: When Type Safety Requires Talking to Yourself
Kotlin's type system is expressive enough to let you write code that is simultaneously statically typed, runtime validated, and ergonomic at the call site. That combination usually requires some ma...

Source: DEV Community
Kotlin's type system is expressive enough to let you write code that is simultaneously statically typed, runtime validated, and ergonomic at the call site. That combination usually requires some machinery โ and understanding why the machinery exists, rather than just how to copy it, is the difference between architecture and cargo-culting. For reference, we will use the RandomPokemon repo. The BaseViewModel in this codebase is a clean example of a pattern where self-referential generics, reified type parameters, and a sealed class hierarchy solve a real problem at a boundary where compile-time types naturally blur. An implementation like this enforces a single, standardized way to consume use case output that makes type mismatches observable before they reach production. The Problem at the UI/Domain Boundary ViewModels sit at a boundary between two distinct type worlds. The domain layer produces ResultState โ a sealed class that carries either a message, an error, or a payload typed as