Sealed classes in Kotlin(Something new in Kotlin)-Chapter-15

Posted by manasvisawant45 on July 7, 2021 2:24 am


Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a set, but cannot have any other type. In a similar way, sealed classes are similar to enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances and each has its own state. For a declaration of a sealed class or an interface we just have to write sealed in front of it. Let us see a simple syntax of how to declare a sealed class.

                        sealed class Example
                        sealed interface Example

Let us have a look at certain features of sealed classes defined in Kotlin:-

1)A sealed class is abstract by itself, it cannot be instantiated directly and can have members.

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

3)Subclasses of sealed classes must have a properly qualified name. They can’t be local nor anonymous objects.

4)enum classes can’t extend a sealed class (as well as any other class), but they can implement sealed interfaces.

Let us see how to write a simple example with a sealed class in Kotlin

sealed class Fruit { 
    class Apple : Fruit() { 
        fun printMethod() 
        { 
            println("Apple") 
        } 
    } 
    class Banana : Fruit() { 
        fun printMethod() 
        { 
            println("Banana") 
        } 
    } 
} 
fun main() 
{ 
    val obj = Fruit.Banana() 
    obj.printMethod() //Output: Banana
  
    val obj1 = Fruit.Apple() 
    obj1.printMethod() //Output: Apple
}

Why do we need sealed classes?

Sealed classes and interfaces define restricted class hierarchies that provide more control over the inheritance. All subclasses of a sealed class are known at compile time. No other subclasses may appear after a module with the sealed class is compiled. For example, code outside the sealed classes can not make use of sealed classes elements, or neither can extend the sealed class. Thus, each object of a sealed class has a type from a limited set that is known when this class is compiled.

Feel free to read the post and comment below.

Below is my android application, and is useful for people who have Google Opinion Rewards to cash out. https://play.google.com/store/apps/details?id=com.manasvi.sawant.rewardtocash

If you wanted to create a website, please visit my Fiverr gig link below or contact me at support@techoceanhub.com. https://www.fiverr.com/share/EdZ9L7