Restricting class hierarchies
In this recipe, we will learn how to restrict the class hierarchies in Kotlin. Before we move ahead, let's understand why this is a cause worth spending our time on.
Getting ready
I'll be using Android Studio to run the code described in this recipe.
How to do it…
When we are sure that a value or a class can have only a limited set of types or number of subclasses, that's when we try to restrict class hierarchy. Yes, this might sound like an enum class but, actually, it's much more than that. Enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances that can contain state. Let's look at an example in the mentioned steps:
- We will create a sealed class named
ToastOperation
. Under the same source file, we will define aShowMessageToast
subclass:
class ShowMessageToast(val message:String):ToastOperation()
- Also, we'll define a
ShowErrorToast
object:
object ShowErrorToast:ToastOperation()
- As you may have noted, I have...