Dart : Sealed Class

Dart : Sealed Class

·

1 min read

Sealed Class

  • To create a known, enumerable set of subtypes, use the sealed modifier. This
    allows you to create a switch over those subtypes that is statically ensured.

  • The sealed modifier prevents a class from bring extended or implemented
    outside its own library. Sealed classes are implicitly abstract.

  • They cannot be constructed themselves.

  • They can have factory constructors.

  • They can define constructors for their subclasses to use.

sealed class Result{}

class Success extends Result {
    final String message;
    Success(this.message);
}

class Error extends Result {
    final String errorMessage;
    Error(this.errorMessage);
}

void main() {
    final result1 = Success('Operation successfull');
    final result2 = Success('Operation failed');

    handleResult(result1);
    handleResult(result2);    

}

void handleResult(Result result) {
    if(result is Success) {
        print('Success : ${result.message}');

    } else if (result is Error){
        print('Error : ${result.errorMessage}');
    }
}
Success : Operation Successfull
Error : Operation Failed

Exited.