Kotlin Sealed Class

When we want to define a limited set of classes, we can use Sealed Classes. We mostly use this class while fetching data from a network. A network call may lead to a success or a failure. Let’s see with an example.

There are three options in our Data class; Success, Error and Loading. All these data classes are inheriting the sealed class Data.

Now let’s create a function and see how we can use this sealed class.

This function will generate a random number between 100-1000 and return data. We know that it will be success.

If we run this code block, output is going to be;

Output Example

🦸🏻 Sources

📕 📓 You can access source code from my GitHub! 🧙🏼‍♀️

--

--