
Making an application (or software in general) is a matter of decisions, most of them are not transcendental but seen together as a whole can lead your code to a land of pleasure full of unicorns or to terrible hell.Serializing kotlin sealed classes (algebraic datatypes) to JSON. A pattern matching can help us to execute the correct action for each case: Result deserialization In order to pass the previous serializer to the Gson implementation, we need something that detects the whole hierarchy of our sealed class: Result.Loading, Result.Ok or Result.Err.Īnd voilá, The registerTypeHierarchyAdapter comes to help us: Result serializationĪbout codification, we have predefined that we’ll save only the Ok result and discard the other states. This adapter could have the follow structure: Result detection How to serialize a sealed class with generics? In theory, we should add a custom adapter to the Google Gson lib that let’s us customize the JSON (de)codification. Although you can find many implementations around, let’s type a simple one: The complex partĪs we are using a Redux like architecture inside Fidesmo app, the Result is part of our state and it must be serialized!! 😱 Popular in languages like Scala, Elm or Rust, it is fantastic because it wraps a value of type T inside a “request context”, where E is the error obtained if the request fails. We use a version of the Either pattern redefined as Result. On the other hand, it is a complex and expensive component.Ĭuriously, the same example can be found inside Fidesmo app codebase: The easy interaction

Sometimes when developing an app, you need to introduce some complexity in order to keep your code neat and clean.Īpplying this idea to a bicycle, an internal-gear hub part comes to my mind: the interaction with it is simple and makes life easier if you stop-and-go when commuting in a big city. JSON serialization and generics in Kotlin.
