brasilwqp.blogg.se

Sealed class serializable kotlin
Sealed class serializable kotlin











sealed class serializable kotlin

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.

sealed class serializable kotlin

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. Override val descriptor: SerialDescriptor = surrogateSerializer.JSON serialization and generics in Kotlin. Private val surrogateSerializer = rializer(tSerializer) for "Error" data: T? = exceptionMessage: String? = null The annotation is not necessary, but it avoids serializing "data = null" ) : KSerializer> class ServiceResultSurrogate( = ServiceResultSerializer::class)ĭata class Success(val data: T) : ServiceResult()ĭata class Error(val exceptionMessage: String?) : ServiceResult() For the sake of simplicity in the example I only represent the exception message. As Animesh Sahu already mentioned there is an issue for this topic that is still open, but the solution using a surrogate suggested by Михаил Нафталь for serialization of Error can actually be used also to serialize the polymorphic ServiceResult, by creating a surrogate that mixes the fields of Success and Error.













Sealed class serializable kotlin