0

https://www.youtube.com/watch?v=2Cl0C-9dK48&list=PLjxrf2q8roU1fRV40Ec8200rX6OuQkmnl

Type Promotion | Decoding Flutter

In the above video, there is the following explanation.

Dart doesn't have sealed classes. That means every class can be extended or even implemented.

I sometimes see the term "sealed classes", but I can't find a definition for this term in Dart. Is there any documents or something that is clearly defined in Dart?

https://dart.dev/guides/language/language-tour#enumerated-types

Note: All enums automatically extend the Enum class. They are also sealed, meaning they cannot be subclassed, implemented, mixed in, or otherwise explicitly instantiated.

I found the above sentence when I searched, but is this the definition of "sealed classes" after all?

森口万太郎
  • 805
  • 6
  • 20
  • 1
    Yes, that is a definition of a sealed class. – mmcdon20 Jun 16 '22 at 02:34
  • 1
    Yes, a sealed class is a class that can't be extended. The remark about "every class can be extended" isn't true. As you've noted, `enum`s can't be extended, nor can `int`, `double`, `bool`, or `String`. – jamesdlin Jun 16 '22 at 04:31
  • Thank you for your reply. Certainly we can draw the conclusions you are pointing out. – 森口万太郎 Jun 19 '22 at 00:07

1 Answers1

2

This link explains the sealed class in dart.

// UnitedKingdom --+-- NorthernIreland
//                 |
//                 +-- GreatBritain --+-- England
//                                    |
//                                    +-- Scotland
//                                    |
//                                    +-- Wales
sealed class UnitedKingdom {}
class NorthernIreland extends UnitedKingdom {}
sealed class GreatBritain extends UnitedKingdom {}
class England extends GreatBritain {}
class Scotland extends GreatBritain {}
class Wales extends GreatBritain {}

Marking not just UnitedKingdom sealed, but also GreatBritain means that all of these switches are exhaustive:

test1(UnitedKingdom uk) {
  switch (uk) {
    case NorthernIreland(): print('Northern Ireland');
    case GreatBritain(): print('Great Britain');
  }
}

As of today, the status is in Progress.

EDIT: The above link is now moved to a new location, and the current status is Accepted.

Update: Thanks, @Abion47, The sealed classes are now merged and here's the GitHub link for that ticket.

Nagaraj Alagusundaram
  • 2,304
  • 2
  • 24
  • 31
  • Thank you for your reply. Even if it becomes possible to use sealed types in the future, is there anything that can only be done with sealed types? Is there something missing in just subclassing the base class and using it without sealed types? – 森口万太郎 Dec 04 '22 at 01:43
  • 1
    Sealed classes have officially been deployed as of Dart 2.19 (and Flutter 3.7). – Abion47 Feb 01 '23 at 18:30