rspec/rules/S3257/dart/rule.adoc

32 lines
1.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Dart supports type inference, a mechanism that automatically infers the type of a variable based on its initial value. This means that if you initialize a variable with a particular value, Dart will assume that this variable should always hold that type of value.
Unnecessarily verbose declarations and initializations of collections make it harder to read the code and should be simplified. Therefore, type annotations should be omitted from collection declarations when they can be easily inferred from the initialized or defaulted value.
== How to fix it
Omit explicit type annotations in collection declarations whenever the type can be inferred from the context.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
var numbers = Set<int>();
var occurrences = Map<String, int>();
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
var numbers = <int>{};
var occurrences = <String, int>{};
----
== Resources
* https://dart.dev/tools/linter-rules/prefer_collection_literals[Dart Lint rule]