In Kotlin, a ‘sealed class‘ is a class that can be subclassed only within its own file. It is a restriction imposed by the Kotlin compiler that prevents other files from creating subclasses of the sealed class. This concept is similar to an ‘enum‘ in Java, but ‘sealed classes‘ can have multiple instances with different properties and behavior.
Here is an example of a ‘sealed class‘:
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
In this example, ‘Expr‘ is a ‘sealed class‘. It has three subclasses: ‘Const‘, ‘Sum‘, and ‘NotANumber‘. The ‘Const‘ and ‘Sum‘ classes are ‘data classes‘ that store a value and expressions respectively. The ‘NotANumber‘ class is an ‘object‘ expression that represents the absence of a value.
‘Sealed classes‘ are similar to ‘enums‘, but they can have more than one instance, and each instance can have different properties and behaviors. ‘Sealed classes‘ are more powerful than ‘enums‘ because they represent a hierarchy of classes with different behavior that might be needed to implement specific functionality. Besides, ‘sealed classes‘ are more flexible and can be used in the same way as other classes.
‘Sealed classes‘ can contain abstract methods and properties. They can be used in ‘when‘ expressions, which are similar to a ‘switch‘ statement in Java. For example:
fun eval(expr: Expr): Double = when (expr) {
is Const -> expr.number
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN
// the `else` clause is not required because all subclasses of `Expr` are covered in the `when` statement
}
In this example, ‘when‘ is used to determine the type of the ‘expr‘ parameter and execute different logic for each type. ‘NotANumber‘ is used to represent an unknown value, similar to ‘NaN‘ in Java.
In conclusion, ‘sealed classes‘ are an important construct in Kotlin that can be used to represent a hierarchy of classes with different behavior. They are more powerful than ‘enums‘ because they can have more than one instance and each instance can have different properties and behaviors. ‘Sealed classes‘ can also contain abstract methods and properties and can be used in ‘when‘ statements.