Repository navigation
Description
In Flutter-team-owned packages (especially plugins where we are wrapping an underlying SDK), we've pretty frequently run into case where we have an enum that's part of the public API surface, and that we expect to add to in the future. Since non-exhaustive switches over enums used to just be a warning, we used to just comment on enums that we wouldn't consider adding a value to be a breaking change. Now that that's changed, and with the introduction of switch expressions, there isn't really a way to use enums without making adding features a breaking change.
It would be great if there were a keyword that could be put on an enum that would invert its exhaustiveness, such that any switch over it had to have a so that it cannot be exhausted by matching values [edited based on discussion later in the thread; the original description did not accurately capture what I wanted]. E.g.,default
nonexhaustive enum ImageFileFormat {
jpeg,
heif,
}Right now, we have this enum, and if next year iOS adds a new image storage format, technically we can't support it as an option without a breaking change to the camera plugin, which isn't what was intended.
(I don't think nonexhaustive is the right keyword, it's just a placeholder.)
Potential alternatives
We've considered some other options for these cases, but don't really love any of them. They all feel like we are working around not being able to express what we want to express, rather than the language letting us say what we want to say in a straightforward way.
Private enum value
enum ImageFileFormat {
jpeg,
heif,
// You need a default case (in exhaustive contexts) because we might add things
_addADefaultCase,
}This is the closest to what we want to express, but it really feels like a hack. On the declaring side we would have to suppress a warning about _addADefaultCase being unused, and on the client side they get an error that looks like:
Error: The type 'ImageFileFormat' is not exhaustively matched by the switch cases since it doesn't match 'ImageFileFormat.library package:camera/camera.dart::_addADefaultCase'.
- 'ImageFileFormat' is from [...]
Try adding a wildcard pattern or cases that match 'ImageFileFormat.library package:camera/camera.dart::_addADefaultCase'.
Most of this text is telling them about the internal details of the force-open implementation, and the second half of the suggested fix is actively confusing (since it sounds like it's suggesting explicitly matching the private case). What we would want is an error that says something like "This enum can have values added in the future, so the switch must contain a wildcard."
Extension types
We could build our own enum out of extension types, but it's quite verbose:
extension type const ImageFileFormat._(int i) {
static const ImageFileFormat jpeg = ImageFileFormat._(1);
static const ImageFileFormat heif = ImageFileFormat._(2);
}It also exposes some weird implementation details. Notably, the quick-fix suggestion if I write a switch that doesn't have a wildcard is int() => ... not _ => ....
Empty classes
We could make the type (e.g., ImageFileFormat) an empty base class and each value an empty subclass, then have clients use patterns to match them. This is also pretty verbose to declare, and definitely doesn't read anything like an enum for clients looking at the API surface. It also makes the value names verbose since they aren't scoped.
Activity
bwilkerson commentedon Jun 25, 2026
@dart-lang/language-team
munificent commentedon Jun 25, 2026
The most robust workaround is to not use an enum:
(You can add a static
valuesgetter andnamegetter too if those are useful.)An enum in Dart is basically just syntactic sugar for a class declaration with some static constants, a couple of members, and an extra bit of exhaustiveness checking.
If you don't want the exhaustiveness checking, you can manually desugar the enum to a class in the same way the compiler would. That gives you all of the same functionality minus the exhaustiveness checking.
However, I admit that doing so is verbose (which is why we added enums to the language in the first place).
I'm not sure if it's worth it to have a modifier on enums to specifically let you opt out of exhaustiveness checking. I'm not morally opposed to it, but complexity always has a cognitive cost, and we have a lot of modifiers on declarations already. We couldn't even reuse an existing class modifier because for enums, the default is backwards. Classes default to open and have to use
sealedorfinalto be closed off, but enums default to closed. So we've had to come up with an opposing modifier (unsealed?) that only worked on enums.I don't know if this use case is common enough to justify that.
FMorschel commentedon Jun 25, 2026
Maybe an assist to make that change from an enum to a final class easier?
bwilkerson commentedon Jun 25, 2026
With dot-shorthands you can omit the class name in the initializer, and by having multiple fields in a single declaration (something I generally dislike) you can avoid duplicating even more code:
I'm not advocating this solution, but it does reduce the verbosity.
stuartmorgan-g commentedon Jun 26, 2026
If it would be useful I could audit the API surface of everything in flutter/packages and see what the breakdown is. (My gut feeling is that this could easily be the majority use case for our public enums.)
stereotype441 commentedon Jun 26, 2026
@stuartmorgan-g I think that would be very useful information indeed!
jellynoone commentedon Jun 27, 2026
As a user of Flutter, I would like to note that I rarely switch over flutter provided enums. I use them as input or transparent values, but as a regular consumer I have no need to actually switch over them. Meaning, even if a new enum value is added, my hunch is that most users wouldn't be affected.
The only users affected, are those who are building on-top of flutter primitives. And there a breaking change would probably be desirable. For instance, if a new format is added and I'm handling it, I would like to be notified about this. Also regardless if the format is expressed as a class or an enum, I would either have to increase my dependency to a version that includes the value or be at a risk of breaking dependents on different versions.
So perhaps it might make more sense to simply have a policy, that flutter considers adding enums a non-breaking change since enums should only be used as input to the Flutter API and not used by clients themselves. And if clients have a need they should create their own enum and convert it at boundaries to the flutter alternative. Similar to how if you're using the pigeon plugin to generate the platform APIs you usually create a user facing enum, that you manually control rather than expose the internal enums the generator produces.
For instance, users who only pass the enum over to the API wouldn't be affected by new additions:
stuartmorgan-g commentedon Jun 28, 2026
That depends entirely on the enum, and the consumer, neither of which we control as package authors.
Publishing a new minor version that people need to require to get new functionality has essentially no impact on the ecosystem. Publishing a new major version causes ecosystem splits and causes a spike of people hitting resolver failures.
There are nearly 450 packages that depend on
camera, for instance. Frequent breaking changes just to add new features would be extremely disruptive to the ecosystem.Pointing to a policy somewhere that says people shouldn't do something they have no way of knowing not to do isn't going to make people feel better if we release a minor version that accidentally causes massive ecosystem breakage because a couple of popular packages do something we hoped they wouldn't.
I would much rather have the compiler express requirements than documentation. See also the addition of things like
sealed.This is not a generally true statement about the enums in the packages in flutter/packages.
(In the particular case of platform interface enums in federated plugins, it's in fact essentially never true.)
Unless, for example, they use the enum of possible input values to build UI. Which is a thing I have seen clients do with several plugins maintained by the Flutter team.
jellynoone commentedon Jun 28, 2026
I agree with everything being said. Perhaps I didn't word my argument quite right.
What I was trying to say is that if as a consumer you want to switch over an enum, you probably want to catch all cases. In this case, if the library adds a new enum value, even if it breaks you, you would probably want to catch it.
However, if you simply pass the value forward to library, any new enum values don't affect you since you don't use the value yourself.
I think I was too much of an idealist here, I assumed a client would create a new enum, they control, specifically to avoid breaking changes or accept the fact they can can be broken. So, for instance instead of FlashMode, a client would create MyFlashMode, with the enum values they are interested in.
My main concern, regarding the proposed solution:
Is that converting enums to this would be a breaking change, when the user requires a value, for instance:
Additionally, if such a transition occurred, and the user wanted to use the new enum value, if they are a library author, they would have to increase the library version dependency either way to ensure the enum value is available. So the benefit of static analysis showing you where the switch is no longer complete is lost, while simultaneously the same requirement to upgrade stays. So, to me such a change would silence analysis errors, while effectively require the same behaviour for clients.
However, if we mainly want to silence warnings for void methods such as:
wouldn't it make more sense to tweak the language to change enum resolutions in void methods to optional?
In other words, if an enum is switched over and no value depends on the result of the switch, wouldn't it be possible for the compiler to issue a warning instead of an error?
For instance:
(Additionally, wouldn't a similar behavior also be desired for other types of pattern matching?)
stuartmorgan-g commentedon Jun 29, 2026
Again, increasing a minor version of a dependency and increasing a major version of a dependency have wildly different impacts on the ecosystem. The behavior I want is to be able to add enum values as a minor version change. If you are fine incrementing the major version of packages you maintain every time you add a feature, then this request isn't going to be useful to you. It would, however, be incredibly useful to my team.
I am not trying to avoid an individual-client-level problem. I am trying to avoid ecosystem-level problems.
Making it so that some very specific constructs don't cause compile failures when a new enum value is added does not address the use case, because package authors have no way to guarantee that clients only use those constructions, and not the many others that would still fail. The proposal here is to have a form of enum where clients cannot write code that will fail to compile on enum addition, such that adding values can safely be done in a minor version.
jellynoone commentedon Jun 29, 2026
But how can this actually be achieved when you need to produce a value and maintain validity?
For instance, how would the initial example work?
Wouldn't this force the user to always provide a default value to support future cases, something like?
In other words, for me as a user, it seems the package would require me to do more work, to support a potential future where a new value is added. In other words, instead of me having to update my dependencies and potentially fix the code once every few months / years, I have to pay a per use cost (defining default behaviour for future values) on every use in order to support the package being able to add new enums without breaking changes. Or am I missing something here?
As a client I'd rather have more frequent breakage than code that has a greater chance to be invalid. (Invalid there I mean relying on default behaviours I have a greater chance of forgetting I put in place). This is why I proposed demoting errors to warnings when the switch over an enum doesn't affect values the compiler needs.
After thinking about this some more, I think you can actually achieve what you are trying to do in a bit of a "hacky" and verbose manner.
The package could have an internal implementation of a sealed class. It would include all future versions. Client facing versions would be marked with other sealed classes representing different versions. The user would then explicitly mark the version they want to use or if they don't mind being broken use the "unsafe" format which includes all versions and has no backward compatibility promises.
With this solution because the client is using
ImageFileFormattheir use cannot be broken unless they explicitly use a later version. similarly due to the availability of the short syntax, if the user uses thePackageApidirectly, they still have full autocomplete and can just type.instead of having to remember and know all enum names.Additionally, you could go a step further and hide individual additions as well, and rely on the short syntax when matching so even the individual additions, wouldn't be available. For instance:
Additionally, when a new major version is released, the additions could then be merged into the root ImageFileFormat enum and old versions deprecated. Thus keeping the verbosity to the minimum.
Would this be an acceptable solution?
stuartmorgan-g commentedon Jun 29, 2026
Yes. That is exactly what the one-sentence version of the feature request said:
I'm aware there are other ways to get the functionality I'm describing; that was also established in the original request:
jellynoone commentedon Jun 29, 2026
Oh... For some reason, I didn't quite register that. (Considering it would require a breaking change and much user action).
Couldn't then the proposed issue be resolved by adding a new annotation and a warning?
For instance:
This way users that don't care about breaking changes can ignore the warning and simultaneously library authors have a way to express they intend to add new enum values in the futures. This way both camps can coexist, and clients can choose for themselves how they want to handle external enums.
stuartmorgan-g commentedon Jun 30, 2026
I'd have to defer to Dart language folks here; I would expect that an annotation wouldn't be able to change fundamental exhaustiveness guarantees that the compiler relies on.
Assuming it's possible, an annotation with a warning would certainly be better than nothing, but I would much prefer an error with an optional lint that people could enable to tell them when an enum
switchis missing any values. That way people couldn't accidentally write code that will fail to compile later, but can still be automatically informed if a new value is added later.34 remaining items
eernstg commentedon Aug 13, 2026
@stuartmorgan-g wrote:
That's a great analysis! I think it illustrates that the notion of 'kinds' of enumerated types needs to be elaborated a bit.
The kinds I mentioned
I mentioned 'behavior refinement' as one kind here. It is characterized by being associated with useful, non-failure behavior in the case where the given enumerated value is unknown. That is, it is by definition not a bug for an application to not know all values. A switch statement would need to have a
defaultcase if the default behavior is non-empty; a switch expression could have a wildcard case at the end returning the default value. No problems here.The other kind I mentioned was 'behavior selection', and the intention was that this should cover all the enumerated types for which it would be a bug if an application has a switch on this type with no case covering one or more values. The scenario would fit a description like "we know we must do something, but we have no idea what to do". I assumed that this kind of scenario would approximately correspond to the enumerated types where a switch would throw an exception, or otherwise cancel and recover from the current activity, when an unknown value is encountered. I also postulated that this behavior would be considered to be a bug, which still seems reasonable to me.
Light and dark mode
How does light, dark, and adaptive light/dark mode fit into this description? Would it be considered to be a bug if an application recognizes light and dark mode, but ignores a request to use adaptive light/dark mode? Would this be OK forever, or would it be an implicit TODO which should be resolved as soon as possible, just not right now? I'm not quite sure what the actual switch statement or expression should do when it encounters the new, unknown
adaptiveLightDarkvalue. Even if the application ...... there's no history determining what the application used to do when this new, unknown value is encountered, because the value is new! We might have a general strategy for this situation (expressed as a default/wildcard case), e.g., we could choose to do nothing if we encounter an unknown value for light/dark mode selection. However, this just puts the situation into the other bucket where we do have a useful default behavior, and the situation is not considered to be a bug.
Values which are irrelevant to an app
It is also possible that none of the switches on the light/dark mode type will ever encounter the
adaptiveLightDarkvalue. This could be true if the value is chosen by logic in the app rather than in the framework or elsewhere, and this logic hasn't been updated to ever chooseadaptiveLightDark. In that case the app could indeed just keep behaving as it used to.This is a new concept that goes beyond the two kinds I mentioned: For a given app A, an enumerated type
Ecould have an app specific subset of the values which is being used by the app A, and all other values of typeEare guaranteed (with some level of confidence) to never occur as the value of an expression of typeEduring the execution of A.How would we be able to know such things? There could be many ways to get there, but the most typical situation would probably be the one that I already mentioned above: Every value of type
Ewhich is encountered during an execution of code in A is ultimately obtained by evaluation of an expression of the formE.id(or.idwith context typeE), and this expression occurs in the code of A. In particular, if A never mentionsE.someValuethen switches in A do not need to coverE.someValue, it would be a value which is simply irrelevant to the code in A.The property is of course undecidable in general, but this kind of ad-hoc reasoning could be used to reach a reasonable level of confidence. Also, I'd expect some enumerated values to be framework provided, in which case an app would not be able to assume that it will never see new values.
If the 'relevant subset' scenario is a fair description of the situation with a specific enumerated type
Ethen we might actually want a new notion of exhaustiveness: Switches onEwould only need to cover all the relevant values ofE. We might want to get a warning if an irrelevant value is ever mentioned in A. On the other hand, it might be very useful to get a diagnostic message if A contains a switch where some relevant values are not covered. This is very similar to the built-in notion of exhaustiveness in Dart, but it is customized to cover just the subset of values which are considered relevant to A.Given that the underlying concept is undecidable, this notion of exhaustiveness might not be a good candidate as a language feature. As a counter-example, static types are dealing with a decidable subspace of an undecidable kind of properties; however, the notion of 'app-relevant values' might easily be too complex to be practical.
On the other hand, @jellynoone's
ImageFileFormatexample illustrates that it is possible to model several related "versions" of an enumerated type, based on severalenumdeclarations andsealedclasses, etc. This could be used to provide several versions of a given enumerated type that applications and published packages could use in order to get their preferred sets of objects, with full exhaustiveness analysis (sealed class), or without (final class), as desired.munificent commentedon Aug 13, 2026
I believe it's a bit of both. The packages in the Flutter framework are unrepresentative of the Dart ecosystem as a whole. Most Dart code is application code with zero other packages depending on it. For that code, no change is a breaking API change. Better static checking for things like exhaustiveness and unreachable cases for the enums the application itself defines is a good thing with little downside.
Most of the remaining non-application code is in library packages whose userbases are a tiny fraction of Flutter's and which appear much less often deeply buried in transitive dependency graphs. Major version bumps can be somewhat annoying but are still fairly easy to handle for these kinds of libraries.
Very widely used packages deep down in the dependency graph have a lot of stability pressure on them that makes evolving them much harder than the rest of the ecosystem sitting on top. This is true of the Dart core libraries, Flutter packages, and key Dart packages like
test,collection, etc.That being said, a feature that is primarily useful for the small number of widely-used packages doesn't mean the feature isn't worth doing. Since the rest of the ecosystem sits on top of those packages, language features that make their maintainers' lives easier or that make it easier to consume those packages can benefit everyone. Class modifiers is an example of that: We don't expect most application developers to both writing them on their own classes. But having them in the classes in the packages they consume makes it easier for those packages to evolve.
So I don't think it's unreasonable to have a modifier on enum declarations to control whether or not they are exhaustive. It is challenging to figure out what the right default should be. Defaulting to non-exhaustive would be consistent with classes and make the modifier obvious:
sealed. But it would be potentially massively breaking (though language version-able) and it's not clear to me that that is the default most users want most of the time. Defaulting to exhaustive like they are today is non-breaking and consistent with other languages like enums in Rust and Swift, but means the modifier has to be flipped compared to classes. :-/davidmorgan commentedon Aug 17, 2026
It's maybe anyway a good idea to improve the diagnostics when one enum constant is private.
Then what you can already do, becomes more useful as it will guide users to the right thing.
bwilkerson commentedon Aug 17, 2026
@johnniwinther Do we / can we get enough information from the exhaustiveness checker to improve the messaging?
johnniwinther commentedon Aug 18, 2026
@bwilkerson It should be possible to improve the message for cases using inaccessible/private values. It somewhat ties into the solution for #61574 for which I have a CL in progress.
leafpetersen commentedon Aug 18, 2026
I'm pretty unconvinced by the discussion here that this is something we would do. The initial issue mentions several tooling shortcomings as reasons not to use the currently available patterns for expressing the desired semantics. Those tooling shortcomings seem like they should be solvable to me without any language changes. The language change itself is unconvincing to me. Enums are a very small targeted bit of syntactic sugar, with the additional property that they define a closed ("enumerated") set of values. An open enum removes the only semantic part (the closed bit), leaving nothing but the syntactic sugar for something that you can already express in a number of ways, notably using classes. Rather than duplicate yet more of the functionality of classes into enums, I'd rather start from the simple class based approach that @munificent describes above:
If this is really too much boilerplate and we consider this an important and broad use case, I'd advocate for exploring in the direction of supporting the enum use case directly using classes with the goal of eventually deprecating and removing the special case of enums, rather than extending enums to handle more of the class patterns.
munificent commentedon Aug 18, 2026
I spent some time discussing this today with @loic-sharma and @leafpetersen.
My general feeling is that it is sort of an irregularity that enum syntax doesn't let you define a non-exhaustive enum. Enum declarations are 99% syntactic sugar for a class declaration with some static constants. The remaining 1% is the "and it's exhaustive". It's annoying (to me) that you can't get the 99% without also the 1%. It's also inconsistent with classes where you can have an exhaustive class hierarchy (using
sealed) or a non-exhaustive class hierarchy (usingfinal).At the same time, adding a modifier for enums is tricky. We realistically can't default to non-exhaustive and then use
sealedto opt in to exhaustiveness. That would be massively breaking to all existing switches on existing enums. It's also not clear that non-exhaustive is the right default. But having to conjure up yet another modifier for enums to opt out of exhaustiveness is not appealing either (unsealed? Ick.) I don't think there's any consensus on the language team that a feature like this is worth doing or what the default and modifier should be.Even if we had consensus that this feature is a thing we would like to do in principle, it seems unlikely that it would be a high enough priority to put design and implementation time into compared to other language features.
However, if what you want is the behavior of enums without the extra exhaustiveness checking, you can get those semantics today. Make a class with some static constants. That's definitely not as concise as an enum declaration. But arguably the resulting code sends a clearer signal to readers. "Enum" sends "closed set" to readers. As Leaf says, "it's right there in the name: enumerated type". If you want a bag of constants that you intend to grow over time without breaking users, an enum is maybe not the right tool to reach for anyway.
So for Flutter, if there are enum-like types where the framework team wants to be able to add more values in the future without breaking users, I'd suggest using a class with some static constants. Converting existing enums to that pattern is a breaking change. (And if we had "unsealed enums" as a language feature, converting to those would be equally breaking.) But at least for new types, you could consider using that class pattern instead of an enum.
For types where you think it is rare that you'll add new values, I'd still encourage you to use enums. They are much friendlier for consumers of the enum type and exhaustiveness checking and unreachable code warnings are helpful for ensuring your code covers all the values with no dead code.
bparrishMines commentedon Aug 19, 2026
This may have been suggested already in some capacity, but could we do a combination of
Adding a
@mustIncludeDefaultCaseto the meta package. This annotation just ensures that whenever the annotatedTypeis used in a switch statement, it must handle the default case. This is similar tomustCallSuperormustBeOverriden.Add a new lint that ensures that when an enum is used in a switch statement, that it MUST include all cases, regardless if there is a default case or not. Something like
must_include_all_cases.This would allow maintainers to opt into requiring the default case and a consumer can still get the benefit of a lint warning when they are missing a case. But I'm not familiar with working with lints or annotations, so I'm not sure of the difficulty of the suggestion.
stuartmorgan-g commentedon Aug 20, 2026
I understand the arguments for why it might not make sense to add the feature at this point, but I would hope that we can at least agree that this is a lot of boilerplate as compared to:
Almost everything in the first version is the same boilerplate copied over and over (which all clients have to wade through when looking at the API; it's not just a one-time cost to implementers), and the only part that isn't a bunch of copy/paste is forcing the author to assign a completely meaningless unique value to each entry by hand. Even worse, that meaningless value creates an entirely unnecessary opportunity for bugs:
This compiles without any warnings, the bug is visually masked by all the boilerplate, and it would be easy for this to ship without anyone tripping over it for a while.
FMorschel commentedon Aug 20, 2026
Also noting here that when migrating from an
enumto a not-enum, anyone who was relying onnamefor whatever will miss that and have to reimplement it manually if they want to continue using it.davidmorgan commentedon Aug 21, 2026
If you want the enum to be serializable in any flexible way--for example allowing migrations of the serialization format--then you need codegen. (Well, not need, but hand-crafted serialization is really expensive to get right.) It's unfortunately very verbose today, but it does at least prevent mistakes. With augmentations it can be quite nice.
munificent commentedon Aug 21, 2026
I agree, but the cost (cognitive load, design, implementation, testing, maintenance, documentation, developer experience, error messages, etc.) to shipping a language feature, even a seemingly simple one, is always higher than people realize.
If we had infinite engineering resources, I would be all for it. But in practice we don't. I don't think we'll say that we will never support this. (For comparison, Rust does support a
#[non_exhaustive]attribute on enums.) I'm just try to set clear expectations that it's likely this feature won't rise to the top of the priority list in the near future.One thing that would help it have higher priority is to convert existing enums to the enum-like class pattern. Because then we have more concrete code in the wild that we can point to and say "if we had this syntactic sugar, here are places that would use it". Right now, it's syntactic sugar for code that might exist, which is a harder sell. It would be a shame if we added support for non-exhaustive enums to Dart and then it turned out not even Flutter could benefit from the syntax because it's too hard to convert the enums and ship the breaking changes.
eernstg commentedon Sep 29, 2026
The amount of boilerplate in an enum-ish class declaration could actually be slightly smaller than in the examples given so far:
This is not that different from the formatting of an actual
enumdeclaration. We do need to putstatic const EnumishThingin front of the list of values, anddart formatputs the first value on the same line as the type annotation, which somewhat disrupts the "visual listness" of the list of values. But we're usingname = ._()rather thanname, and if there are constructor arguments then we'd usename = ._(the, args)rather thanname(the, args), which makes the boilerplate rather modest.I removed the
indexmember and made no attempt to supportvalues, because those two concepts seem to be misguided for a non-exhaustive type. I think this could be appropriate for new enum-ish types. It might be too much of a breaking change for existing ones, butindexand/orvaluescan of course be added, if needed.The
nameproperty could be useful, though, so perhaps a typical enum-ish declaration could look like this:loic-sharma commentedon Sep 29, 2026
I think we do need an
indexorvaluemember for matching to work properly withconst:eernstg commentedon Sep 30, 2026
Oh, you're right, we can't allow canonicalization to let two different names denote the same object!
That's definitely crucial to remember every time an enum-ish class is created. This is a quite error-prone property of the enum-ish design pattern—we aren't getting any help from the static analysis when some of the enum-ish values collapse to the same object. @stuartmorgan-g's example using
EnumishThing._(2)twice shows very convincingly how easy it is to make this mistake.An index (avoiding the
EnumishThing._(2)bug) would prevent this, but so would a name (assuming that theStringused as the name is different from the names of all other values of the same type). We just need to make sure each enum-ish value has a state that differs from the state of every other value of the same type. The habit of writingtheName = ._("theName")would suffice.However, we do get this guarantee ("different elements in the list of values are never the same object") as well as some others when we use a real
enumdeclaration.For example, every instance of the type is guaranteed to be shown as one of the objects created in the list at the beginning of the
enumbody. This is a different kind of exhaustiveness (it isn't about checks on switch statements/expressions, it is about the human reader who wants the guarantee that every value of the typeEnumishThingcan be found by looking at the top of the class body ofEnumishThing). For example, nothing prevents the following:When developers can't (easily) find the complete list of values, they may not be able to determine correctly whether the treatment of the default case is appropriate. For example, we might have a particular switch statement that does nothing when the enum-ish value isn't one of the known values. Now assume that an extra value is added. Who says that the correct way to handle this new value is also to do nothing? Perhaps we should we should do the same thing as one of the existing known values, or perhaps we should do a completely new thing.
The point is that a switch statement/expression with a default case doesn't remove the need to consider the correctness of the code in the default case, it just hides the actual values handled there. A particularly dangerous situation arises when that invisible set of values changes, and this makes me think that it could be useful to allow for exhaustiveness analysis in a way which is clearly documented to be breakable ("you can do this, but it's your problem if and when it breaks").
We might take another look at the design that I mentioned here:
The point is that the "official" enum-ish type is
E, which is non-exhaustive. Presumably, most developers will just useE.However, the underlying values are real enum values, which means that the full exhaustiveness analysis is available to developers who wish to accept this "your problem if it breaks" contract. I tend to think this could be a useful middle point between an exhaustive and a non-exhaustive treatment, and it avoids the "several values collapse to the same object" bug.
Note that
_E, being a private type, cannot be denoted in code outside the library where it is declared. This ensures that the type doesn't propagate very far (it can't be a type annotation, it can only be the type of an expression and the inferred type of a local variable). In other words, it can be used in an implementation, but it can't be used in an API. This essentially implies that we can grep forexhaustin order to find all the locations where the exhaustiveness based breakage may occur, which would also suffice if an organization wishes to ensure that it doesn't occur at all.