Kotlin is a cutting-edge, open-source language used for creating cross-platform mobile applications. It is a very user-friendly language that is also very simple to maintain and troubleshoot. Kotlin uses features like classes and objects. The idea of classes is complex and wide-ranging. For example, Kotlin has features like sealed classes, data classes, abstract classes, and enum classes that allow you to dig deeper and examine that class's options. In this tutorial, you will learn all about Sealed class in Kotlin.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Is a Sealed Class in Kotlin?

A significant additional class type not seen in Java is introduced in Kotlin. The new type is known as a sealed class in Kotlin. A sealed class restricts the hierarchy of classes. The term "sealed" is used right before the class name to declare a class as sealed. When you have a sealed class declaration, the compiler recognizes that the class is sealed automatically. It serves as a marker to limit the hierarchy of classes.

Syntax of sealed class:

Sealed_Class_In_Kotlin_1

To define a sealed class, simply place the sealed keyword before the class modifier. The constructors of sealed classes are by default protected, which is another distinctive trait.

Now, understand when and why Sealed classes in Kotlin are used.

When and Why Are Sealed Classes Used?

Sealed classes are intended to be utilized. When just a small number of options are available for a value and each of these options differs in functionality. 

Kotlin's sealed class is one of the built-in classes that can be used to prevent users from inheriting a class. It can be sealed using the sealed keyword. The compiler is immediately informed that a class is sealed if you use and declare it with the sealed keyword. As a result, the class cannot be extended in this way with additional child classes.

Now you will understand some important points of the sealed class in Kotlin.

Important Points of the Sealed Class

  • A sealed class's subclasses must all be specified in the same file as the sealed class itself.
  • Sealed classes are abstract and can have abstract members.
  • Public constructors cannot be used in sealed classes.
  • Sealed classes cannot be instantiated directly.

Now, you will understand how to create a sealed class in Kotlin.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Creating a Sealed Class

Although a sealed class is allowed to have subclasses, they must all be specified in the same Kotlin file.

Sealed_Class_In_Kotlin_2

In this example, the sealed class is named “First.” and has two subclasses defined. The first subclass is named Peter, and The second subclass is named Bob. You have defined print() functions in these subclasses, in which you have the Kotlin println function. 

The main function for showing the message from the subclasses follows. The "obj1" and "obj2" objects are subclasses that we have built. The subclasses "Peter" and "Bob" are being called by "obj1" and "obj2," respectively. The print() function is used to display the content of the subclasses on these objects "obj1" and "obj2."

Go ahead and move on to the next topic of sealed class in Kotlin.

Sealed Class With When Expression

The if, else, and switch case expressions used in Java are replaced by the when expression in Kotlin. These phrases ensure all possibilities have been considered by using the else branch. 

The when expression makes sure that all of the sealed class's subclasses are handled. If you neglect to handle a specific subclass of the sealed class, it will show an error. The else block is no longer required. However, you must use when as an expression and not a statement for it to be effective.

Now, have a look at this example.

Sealed_Class_In_Kotlin_3

In the code above, the sealed class is named Gadget. In a sealed class, you have three subclasses identified as Laptop, Phone, and Airpods. String values provided to these subclasses are present. Then, there is a display() function that accepts an object of type Gadget and displays a message corresponding to the kind of class sealed.

The "when" statement is present here instead of the "else" clause. You have passed a sealed class to the "when" expression, which will handle all cases. The word "is" serves as a filter to see if the class fits into one of the following categories in the "when" statement. Only classes require the use of the "is" keyword. 

Below is the output of the above example:

Sealed_Class_In_Kotlin_4

Now, you will have a look at the difference between sealed class and enum.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Difference Between Sealed Class and Enum

You have the freedom to have different kinds of subclasses and the ability to contain the state, thanks to sealed classes. The crucial thing to keep in mind in this situation is that any subclasses that extend Sealed classes must either be nested classes of Sealed classes or must be declared in the same file as Sealed classes.

Enum types are constants, making it challenging to maintain various instance states.

A sealed class subclass can have several instances, each with its own state, unlike an enum constant, which only exists as a single instance.

In an enum class, you cannot define various functions in each enum constant.

A sealed class allows you to add various custom constructors as necessary easily.

If you're eager to gain the skills required to work in a challenging, rewarding, and dynamic IT role - we've got your back! Discover the endless opportunities through this innovative Post Graduate Program in Full Stack Web Development course designed by our partners at Caltech CTME. Enroll today!

Conclusion

In this tutorial on Sealed classes in Kotlin, you understood when and why sealed classes are used and the important points of Sealed classes. You also learned about the creation of sealed classes and using Sealed classes with when. Additionally, you learned about the differences between sealed classes and enum classes and a few other topics in detail using examples. 

If you are looking to build a software development career, you can check the Post Graduate Program in Full Stack Web Development by Simplilearn. It might be the best option for assisting you in advancing your profession.

Do you have any questions about Sealed classes in this Kotlin tutorial? If you do, you can include them in the comments section below. Your questions will be addressed by us at the earliest.

About the Author

Harsh BhardwajHarsh Bhardwaj

Harsh is a Research Analyst at Simplilearn. He has a good hand at C++, Java, CSS, SQL, and a good grasp of Kotlin language. Harsh is quite interested in traveling, spirituality, and playing football.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors