Know about kotlin sealed classes with example

Sealed classes

Sealed classes in Kotlin are another new concept we didn’t have in Java, and open another new world of possibilities.where an object or a worth can have one in all the kinds from a limited set of values. you’ll consider a sealed class as an extension of enum class. The set of values in enum class is additionally restricted, however an enum constant can have only single instance while a subclass of a sealed class can have multiple instances

Why we need a Sealed class?

Lets first understand the necessity of a sealed class. within the following example we’ve got a category Colorwhich has three subclasses Red, Orange and Blue.

Here the When expression in eval() method must use a else branch else we’ll get a compilation error. Now if we attempt to add a subclass to the category Color, the code within the else branch will execute which may be a default code. The compiler should warn us that the code for the newly added sub class doesn’t exist and thus we must always get a warning or error for adding a new subclass without adding the logic in when expression. This problem is solved using Sealed class.

Sealed classes and when

Sealed classes are mostly used with when statements where  their types and each of the subclasses act as a case. Moreover, we all know that the Sealed class limits the categories. Hence, the else a part of the when statement may be easily removed.

open class Color{
    class Red : Color()
    class Orange : Color()
    class Blue : Color()
fun eval(c: Color) =
        when (c) {
            is Color.Red -> println("Paint in Red Color")
            is Color.Orange -> println("Paint in Orange Color")
            is Color.Blue -> println("Paint in Blue Color")
            else -> println("Paint in any Color")

fun main(args: Array<String>) {
    val r = Color.Red()

Rules of a Sealed class in Kotlin

  • We cannot create the thing of a sealed class which implies a sealed class can’t be instantiated.
  • All the subclasses of a sealed class must be declared within the identical file where the sealed class is said.
  • The constructor of sealed class is by default private and that we cannot make it non-private.

Implementing Kotlin Sealed Classes

fun main() {
   // val  tile=Red("Mushroom",25)
    val  tile:Tile=Red("Mushroom",25)
    val  tile2=Red("fire",30)
   // println("${tile.points}-${tile2.points}")

    val  points:Int=when(tile)
        is Blue -> tile.points * 2
        is Red -> tile.points*5

sealed class Tile
class Red(val type:String, val points:Int):Tile()
class Blue( val points:Int):Tile()

You may also like...

shayan May 2, 2021
| |
nice post