Kotlin sealed class for success and error handling

Handling errors has never been easy for Java programming language since the lack of supports from the Java compiler.

Seanghay
The Startup
2 min readJun 27, 2020

--

A well-known Use-case

Sealed class is not new in other programming languages such as C# and Scala. The sealed class provides a way to organize our code to look a lot nicer and easy to work with.

An example of how to use Sealed class for handling error and success

As you can see in the example above that there is no need to manually cast objects. Kotlin compiler knows what data type it should be.

Sealed classes work well with LiveData and ViewModels

Oftentimes, we use LiveData to store data from APIs or databases, however, data from those I/O operations could cause failure, so the best way to handle those errors and successful responses is to use Sealed classes.

Basic sealed class for handing results.

In our ViewModels, it would look something similar to this. I assume that you all familiar with Kotlin Coroutines.

Basic usage of Sealed class with LiveData in ViewModels

After this, we can finally observe it from our Activities or Fragments.

Observing the result LiveData in a fragment

Look through, these sample codes, we might be thinking it’s the best way to work with, but there is more we can do to improve it by using Kotlin extension functions.

Get rid of `when` keyword

when in Kotlin is great for checking conditions however it seems boring when we use it again and again for our ResultOf object. So the way to fix that is to create extension functions.

And here our new result

doIfSuccess and doIfFailure are an inline function so there is no runtime overhead. They will get removed when compiling into Java bytecode.

`ResultOf` Transformations

Currently, the ResultOf does not support mapping its value into something else. For example, we want to get the first post of the list of posts in ResultOf object. So let’s write another extension function for that.

By creating this extension function, we can finally map the successful state into something else we prefer.

Default Value when Failure happens

Sometimes, we want to ensure that we always get a successful result even if there was an exception. To do that, we need to provide it a default value.

Now we can specify our default value.

By setting the default value, we have only a successful state to handle.

Conclusion

Kotlin sealed class is powerful for handling different states from I/O calls, but this is only one use-case for it. There are many more use-cases that we can use to improve the readability and consistency of our codes.

Library (Updated)

I just released this as a library so that you can easily import it.

--

--