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.

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.

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.

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.

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

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

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.

seanghay/result-of
This is not the same as standard Kotlin Result because it is a sealed class not an inline class.