Kotlin tutorial for Beginners – Kotlin Sealed Classes

Hits: 3

Kotlin Sealed Classes

In this article, you will learn about Sealed class, how they are created, and when to use them with the help of examples.


Before going into details about sealed classes, let’s explore what problem they solve. Let’s take an example (taken from official Kotlin website – Sealed classes article):


class Expr
class Const(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

fun eval(e: Expr): Int =
        when (e) {
            is Const -> e.value
            is Sum -> eval(e.right) + eval(e.left)
            else ->
                throw IllegalArgumentException("Unknown expression")
        }

 

In the above program, the base class Expr has two derived classes Const (represents a number) and Sum (represents sum of two expressions). Here, it’s mandatory to use else branch for default condition in when expression.

Now, if you derive a new subclass from Expr class, the compiler won’t detect anything as else branch handles it which can lead to bugs. It would have been better if the compiler issued an error when we added a new subclass.

To solve this problem, you can use sealed class. As mentioned, sealed class restricts the possibility of creating subclasses. And, when you handle all subclasses of a sealed class in an when expression, it’s not necessary to use else branch.


To create a sealed class, sealed modifier is used. For example,

sealed class Expr

Example: Sealed Class

Here’s how you can solve the above problem using sealed class:


sealed class Expr
class Const(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
object NotANumber : Expr()


fun eval(e: Expr): Int =
        when (e) {
            is Const -> e.value
            is Sum -> eval(e.right) + eval(e.left)
            NotANumber -> java.lang.Double.NaN
        }

As you can see, there is no else branch. If you derive a new subclass from Expr class, the compiler will complain unless the subclass is handled in the when expression.


Few Important Notes

  • All subclasses of a sealed class must be declared in the same file where sealed class is declared.
  • A sealed class is abstract by itself, and you cannot instantiate objects from it.
  • You cannot create non-private constructors of a sealed class; their constructors are private by default.

 


Difference Between Enum and Sealed Class

Enum class and sealed class are pretty similar. The set of values for an enum type is also restricted like a sealed class.

The only difference is that, enum can have just a single instance, whereas a subclass of a sealed class can have multiple instances.

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.