Signup/Sign In

Kotlin Sealed Class

In this tutorial we will learn about Kotlin Sealed class. Sealed classes are new in Kotlin and were not present in Java.

A sealed class is used to represent restricted class hierarchies. It means the object of sealed class can have only one of the defined types. Let us understand it with the help of an example.

Suppose there is a need to declare classes based on types of questions in an examination. The question type can be Easy, Moderate or Difficult. Now we want to create a class Question and all the question type should inherit this class. We also want to make sure that apart from this usecase, no other class should inherit this Question class.

This is what we can achieve through Sealed classes. A class can have some specified child classes only. This is useful when we know all the subtypes of a parent class and don't want to create a child class aprt from what we know.

Difference between Sealed class and Enum class

The similar functionality is also provided by Enum. In Enum, we can have particular types defined in it. The key differences between Sealed classes and Enums are:

  • Each enum instance exists only as a single instance, whereas a child class of a sealed class can have multiple instances. It means each object of child class(of sealed class) can have a state.

  • In Enum, each instance has same set of properties and functions. But in Sealed class, different child classes can have different set of properties and functions.

  • Child classes of a sealed class can be of different types like: data, object or normal class.

Creating Kotlin Sealed class

Sealed classes are created using the sealed keyword. It is important to note that all the sub classes of a sealed class must be declared in the same Kotlin file. If we try to create a sub class of a sealed class in other Kotlin file, we will get an error. The sealed class is abstract by default. It means we can't instantiate sealed classes.

Let us create a sealed class named Question and create three sub classes Easy, Moderate and Difficult for it:

// this is our Kotlin sealed class
sealed class Question{
    // these are child classes
    class Easy(var mark: Int, var time: Int): Question()
    class Moderate(var mark: Int, var time: Int, var hint: String): Question()
    class Difficult(var mark: Int, var time: Int, var hint: String, var solution: String): Question()
}

fun main() {
    val easyQuestion = Question.Easy(1, 1)
    println("The marks and time limit for an easy question is ${easyQuestion.mark} mark and ${easyQuestion.time} min")
}


The marks and time limit for an easy question is 1 mark and 1 min

As you can see in the example above, we can use sealed classes for use cases where we know what all child classes are required and created classes strictly serves a single purpose, like in the code example above, we have a Question class which is inherited by 3 child classes, that's it.

Kotlin Sealed class: when expression

We often use a sealed class with a when expression. It is because the when expression ensures that all the sub classes of the sealed class are handled. It will give an error if we forgot to handle a particular sub class of the sealed class. Now there is no need to have an else block. But it will work only if you use when as an expression and not as a statement.

Let us modify above example to use the when expression:

sealed class Question{
    class Easy(var mark: Int, var time: Int): Question()
    class Moderate(var mark: Int, var time: Int, var hint: String): Question()
    class Difficult(var mark: Int, var time: Int, var hint: String, var solution: String): Question()
}

fun questionDetail(question: Question): String {
    return when(question){
        is Question.Easy -> "Easy question Mark: ${question.mark} Time: ${question.time} min"
        is Question.Moderate -> "Moderate question Marks:  ${question.mark} Time: ${question.time} min and Hint: ${question.hint}"
        is Question.Difficult -> "Difficult question Marks:  ${question.mark} Time: ${question.time} min Hint: ${question.hint} and Solution: ${question.solution}"
    }
}
fun main() {
    val easyQuestion = Question.Easy(1, 1)
    val difficultQuestion = Question.Difficult(5,6,"substitution method", "x = 5, y = 3")
    println(questionDetail(easyQuestion))
    println(questionDetail(difficultQuestion))
}


Easy question Mark: 1 Time: 1 min
Difficult question Marks: 5 Time: 6 min Hint: substitution method and Solution: x = 5, y = 3

Using the when expression with Sealed classes child class, we can easily define conditions to perform specific action based on the child class of the sealed class.

Summary

In this tutorial we learned about Kotlin Sealed class, why they are useful, how to define a sealed class and its child classes along with code examples and using the when expression with sealed classes in Kotlin. In the next tutorial we will discuss about Kotlin Generics.



About the author:
I'm a writer at studytonight.com.