Left Index

Kotlin Sealed Class

A sealed class is used for representing restricted class hierarchy where an object or a value can have one of the types from a limited set of values. You can think of a sealed class as an extension of enum class. The set of values in enum class is also restricted, however an enum constant can have only single instance while a subclass of a sealed class can have multiple instances.


In layman terms, as the name suggests, sealed classes are sealed or closed, hence making them restricted.

Implementing a sealed class is actually very simple. Let's use as an example a set of operations that can be applied to integers and colors

The implementation would be as follows:

How to use sealed class
sealed class Colors {
	class Red : Colors()
	class Green : Colors()
	class Yellow : Colors()
	class Pink : Colors()
}

sealed class Operation {
	class Add(var arg1: Int, var arg2: Int) : Operation()
	class Minus(var arg1: Int, var arg2: Int) : Operation()
}

In above code snippet we create two sealed class. One is for using for identify for color and second is used for perform sum and subtraction operation. Let's see how to use:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	whichColor(Colors.Red())
	whichColor(Colors.Pink())

	println()
	
	evalute(Operation.Add(20, 30))
	evalute(Operation.Minus(20, 30))
}

fun evalute(opr: Operation) {
	when (opr) {
		is Operation.Add -> println("Addition is: ${opr.arg1 + opr.arg2}")
		is Operation.Minus -> println("Substraction is: ${opr.arg1 - opr.arg2}")
	}
}

fun whichColor(color: Colors) {
	when (color) {
		is Colors.Red -> println("Selected color is Red")
		is Colors.Green -> println("Selected color is Green")
		is Colors.Yellow -> println("Selected color is Yellow")
		is Colors.Pink -> println("Selected color is Pink")
	}
}

sealed class Colors {
	class Red : Colors()
	class Green : Colors()
	class Yellow : Colors()
	class Pink : Colors()
}

sealed class Operation {
	class Add(var arg1: Int, var arg2: Int) : Operation()
	class Minus(var arg1: Int, var arg2: Int) : Operation()
}
Output:
Selected color is Red
Selected color is Pink

Addition is: 50
Substraction is: -10

Rules of a Sealed class in Kotlin

  • We cannot create the object of a sealed class which means a sealed class cannot be instantiated.
  • All the subclasses of a sealed class must be declared within the same file where the sealed class is declared.
  • The constructor of sealed class is by default private and we cannot make it non-private.