Kotlin Seal Class _kotlin

Source: Internet
Author: User

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

(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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.