Ronnie Atuhaire
Ronnie Atuhaire's Blog 🤓

Ronnie Atuhaire's Blog 🤓

Kotlin Sealed Classes

Kotlin Sealed Classes

Subscribe to my newsletter and never miss my upcoming articles

Hey buddy👋, welcome back to my blog. Today, we shall continue from where we stopped in the last tutorial in this series.

So What Are Sealed Classes?

In most programming languages, sealed classes are classes that cannot be inherited by any class but can be instantiated.

image.png A sealed class is often used to encapsulate a logic that needs to be used across the program but without any alteration to it.

Sealed Classes allow us to fix type hierarchies and forbid developers from creating new subclasses.

Declaration Of Sealed Classes

To declare a class as a sealed class we need to add a keyword sealed just before the class keyword.

sealed class Example

Implementation

Let’s check by defining a simple sealed class that has different types of classes:

 sealed class Month {
        class January(var numberOfDays: Int) : Month()
        data class February(var displayName: String) : Month()
        object March : Month() {
            var numberOfDays: Int = 0
            var displayName: String = "March..."
        }
    }

Now let's check out how to access the sealed class by creating objects and passing the values

fun sampleAccess(month: Month) = when (month) {
        is Month.January -> println("Number of days in January${month.numberOfDays}")
        is Month.February -> println("Display name of February ${month.displayName}")
        is Month.March -> println("Number of days & Display name of March ${month.numberOfDays} && ${month.displayName}")
    }

 fun sample() {
        val jan = Month.January(31)
        val feb = Month.February("Feb")

        eval(jan)
        eval(feb)
    }

Sealed Class Rules:

🔹 Sealed classes are abstract and can have abstract members.
🔹 Sealed classes cannot be instantiated directly.
🔹 Sealed classes cannot have public constructors (The constructors are private by default).
🔹 Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration.
🔹Sealed classes subclass can have subclasses outside of the sealed class file.

Constructors of sealed classes can have one of two visibilities: protected (by default) or private.

Use Case

Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type.

Can also help in performance optimisation

Why Sealed Class over Abstract Class?

Sealed classes are abstract by themselves, and cannot be instantiated directly. So let’s take a pause here.

image.png If Sealed classes are abstract by default, why can’t we use an abstract class instead of a sealed class in the first place?

Well, the catch here is an abstract class can have its hierarchies anywhere in the project, whereas a sealed class should contain all the hierarchies in the same file.

Sealed Interfaces

As of Kotlin 1.5, interfaces can also have the sealed modifier, which works on interfaces in the same way it works on classes: all implementations of a sealed interface should be known at compile time.

One of the advantages of sealed interfaces over sealed classes is the ability to inherit from multiple sealed interfaces. This is impossible for sealed classes because of the lack of multiple inheritances in Kotlin.

Sealed Class with when Expression

In the example above, I used when expression and we have not yet learnt it but sit tight, we shall look at this later.

A sealed class is most commonly used with a when clause, as the types to which a sealed class reference can conform to are limited. This completely eliminates the use of else clause.

We shall look at this later.

Why sealed Class Over enum?

Sealed classes give us the flexibility of having different types of subclasses and also containing the state.

We shall look at enum classes in the next blog.

Sealed Classes In Python

Python doesn't implement sealed classes, but you still can hack your own". But, would you know if this is a clean hack? You know, it won't break stuff or is highly discouraged or simply make the code runs slower since most people use sealed classes as a performance measure.

You can use metaclasses as a hack to this, but my question is why??
Read the discussion on Stack Overflow.

Read More:

Techopedia
Pro Android Dev
Official Docs

Conclusion

Sealed classes can be an invaluable tool for our API design toolbox. Allowing a well-known, structured class hierarchy that can only ever be one of an expected set of classes can help remove a whole set of potential error conditions from our code, whilst still making things easy to read and maintain.

We have covered quite a lot today and it may seem a lot to take in! Just hold on a little longer as you practice and things will start making sense soon.

If you enjoyed reading, consider subscribing and reacting to this with love by sharing, commenting and any criticism is much welcome.

🔹Follow me on Twitter :

Ronnie Atuhaire 🤓

 
Share this