Kotlin Sealed Class
Kotlin Sealed Class represent restricted class hierarchies, where a value can have a type from a restricted set.
Sealed Class Example
Following is an example of sealed class and sub-classes that extent sealed class.
sealed class ArithmeticOperation
class Add(var a: Int, var b: Int): ArithmeticOperation()
class Subtract(var a: Int, var b: Int): ArithmeticOperation()
class Multiply(var a: Int, var b: Int): ArithmeticOperation()
class Divide(var a: Int, var b: Int): ArithmeticOperation()
A value of type ArithmeticOperation
is restricted to Add
, Subtract
, Multiply
and Divide
.
This situation may look similar to that of Kotlin Enum. But the difference between Enum and Sealed Classes is that, in Enum there is only one value for each class type, whereas in Sealed Class, there could be multiple object instances for a class type (whose parent is a sealed class).
About Sealed Classes
- A Sealed Class have specific number of sub-classes.
- Location
- All the classes that directly inherit a sealed class should be present in the same Kotlin file.
- Constructors
- Sealed Class cannot have non-private constructors.
- Private is the default access modifier for constructors in Sealed Class.
- Abstract
- By default, a Sealed Class is abstract.
- Hence, a Sealed Class cannot be instantiated and all other properties pertaining to Abstract Class hold for a Sealed Class.
Example 1 – Kotlin Sealed Class with when expression
In this example, we have a sealed class ArithmeticOperation
with four sub-classes: Add, Subtract, Multiply and Divide. We will use when expression to demonstrating the usage of Sealed Class.
Kotlin Program – example.kt
fun main(args: Array<String>) {
var a = 4
var b = 3
var operation1 = Add(a, b)
var result1 = execute(operation1)
println("Addition : "+result1)
var operation2 = Subtract(a, b)
var result2 = execute(operation2)
println("Subtraction : "+result2)
var operation3 = Multiply(a, b)
var result3 = execute(operation3)
println("Multiplication : "+result3)
var operation4 = Divide(a, b)
var result4 = execute(operation4)
println("Division : "+result4)
}
sealed class ArithmeticOperation
class Add(var a: Int, var b: Int): ArithmeticOperation()
class Subtract(var a: Int, var b: Int): ArithmeticOperation()
class Multiply(var a: Int, var b: Int): ArithmeticOperation()
class Divide(var a: Int, var b: Int): ArithmeticOperation()
fun execute(op: ArithmeticOperation) = when (op) {
is Add -> op.a + op.b
is Subtract -> op.a - op.b
is Multiply -> op.a * op.b
is Divide -> op.a / op.b
}
This example could be considered a special case, where Kotlin When is used as an expression. In the execute()
function, Kotlin Compiler makes sure that all the classes from the allowed sub-class set are addressed.
Output
Addition : 7
Subtraction : 1
Multiplication : 12
Division : 1
Conclusion
In this Kotlin Tutorial, we learned about Sealed classes in Kotlin, and how to use them in programs with the help of examples.