cast_to_extension_type
Reports a cast to an extension type, such as value as Meters. Call the extension type’s constructor instead.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- writes a call of the representation constructor
What it reports
Section titled “What it reports”A cast to an extension type: value as Meters. An extension type exists only while the code is compiled. At run time its values are values of the representation type, so the cast checks that type alone: -3 as Meters passes, and so does every int.
It does not report:
- a cast from an extension type to another type;
- a cast of a value that already has the extension type, which is the analyzer’s unnecessary cast.
A cast reads as a check. An extension type often stands for a promise the representation does not keep by itself, such as a positive length or a valid identifier, and the cast keeps none of it.
The rule is advisory because a cast of a trusted value is harmless, only misleading.
Example
Section titled “Example”Meters lengthOf(Object value) => value as Meters;Meters lengthOf(Object value) => Meters(value as int);The fix writes Meters(value), which does what the cast did and says so. It is offered only where that compiles:
- the cast is to a type that is not nullable;
- the value already has the representation type;
- the representation type is not itself an extension type;
- the representation constructor is public, or of the same library.
The fix calls the representation constructor, not a validating constructor the extension type may have.
Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// Every length of this sensor is in meters already.// ignore: assay/cast_to_extension_type// ignore_for_file: assay/cast_to_extension_type silences it in a whole file, and // ignore: cast_to_extension_type without the prefix works too. See Suppressions.