A sealed class is used to represent a restricted class inheritance structure: When a value is a finite set of
Type, and cannot have any other type. In a sense, they are extensions of the enumeration class: A collection of values for the enumeration type
is restricted, but there is only one instance of each enumerated constant, and the sealed class
Can have multiple instances that can contain states.
To declare a sealed class, you need to add the sealed modifier before the class name. Although sealed classes can also be
has subclasses, but all subclasses must be declared in the same file as the sealed class itself. (Before Kotlin 1.1,
The rule is stricter: subclasses must be nested inside the sealed class declaration.
Sealed class Expr
data Class Const (Val number:double): expr ()
data Class Sum (Val e1:expr, Val e2:expr): Expr (
Object notanumber:expr ()
fun eval (expr:expr): Double = When (Expr) {are
Const-> expr.number is
Su M-> eval (expr.e1) + eval (expr.e2)
notanumber-> Double.NaN
}
Kotlin
(The previous example uses an additional new feature of Kotlin 1.1: The possibility of data class extensions, including sealed classes, for other classes.)
)
Note that classes that extend the sealed class subclass (the indirect successor) can be placed anywhere, without having to
The same file.
The key advantage of using a sealed class is that when you use the when expression, you can
If the validation statement overrides all cases, you do not need to add another ELSE clause to the statement.
Fun eval (expr:expr): Double = when (expr) {was
expr.const-> expr.number is
expr.sum-> eval (expr.e1) + eval (EXPR.E2)
Expr.notanumber-> Double.NaN
//no longer need ' else ' clause, because we've covered all the cases
}
Kotlin