Seal the Deal with Kotlin — A Look at Sealed Classes and Sealed Interfaces
How Sealed Classes and Interfaces can improve your coding experience
If you’ve ever come across the sealed
keyword in Kotlin, you might have wondered why it’s part of the language and how you can use it. In this article, I am going to discuss the reasoning behind the feature and also present some common use cases. If you’re coming from Java, you will also benefit from this article because with Java 17 sealed classes and interfaces were added to the language (later than Kotlin but still). The sealed
keyword in Kotlin provides a valuable feature for developers by restricting inheritance and enabling exhaustive handling. It ensures a closed set of subclasses, facilitates safer code, and allows for expressive modeling of complex systems and APIs.
The sealed keyword has been part of Kotlin since its initial public release versions, however, it was only useable for classes, not interfaces. With Kotlin 1.5 (released in May 2021), two important improvements were added to the sealed
feature. Join me to learn about all of this in the following sections.
What Is The Sealed Keyword And How To Use It
When we talk about sealed classes and interfaces, we discuss the idea of limiting…