Variables of type `void` should not be assigned a value.
== Why is this an issue?
Unlike other languages where `void` is the absence of a type (and related value), `void` in Dart is a type, which is not compatible with any other type, since it is conceptually a supertype of `Object`.
Therefore, in Dart it's possible to write the following code:
[source,dart]
----
void x = 3; // A variable of type void can be assigned a value of type int
void f(void x) => x; // A function that takes a void input argument and returns it as output
----
The variable `x` declared above, and the result of `f(x)` are effectively of type `void`. However, while `void` variables can be declared, initialized and even computed, they cannot be used by any function that expects a non-`void` type, by the very definition of `void` type.
[source,dart]
----
print(x); // Error: This expression has type 'void' and can't be used.
print(f(x)); // Error: This expression has type 'void' and can't be used.
* `dynamic` variables, like `void` ones, can be assigned values of any type, and, unlike `void` variables, can be assigned to any non-`dynamic` variable
Notice that, because `void` is a type, it can be used as a valid type parameter for a generic class, and that can lead to indirect or "hidden" `void` assignments:
[source,dart]
----
class Wrapper<T> {
T value;
Wrapper(this.value);
}
void main() {
Wrapper<void> w = Wrapper(3); // This is a "hidden" assignment to void
w.value = 3; // This is an explicit assignment to a field of type void
}
----
Another example of a "hidden" assignment to `void` is when assigning generic unconstrained type parameters in generic methods:
[source,dart]
----
void f<T>(T x, T y) {
y = x; // This is a "hidden" assignment to void
T z;
z = x; // This too, is a "hidden" assignment to void
}
----
However, such scenarios are not reported by the rule because for any non-`void` type `T`, the assignment is valid. On the other hand, calling the function `f` with anything other than `void` parameters will be reported as an issue:
[source,dart]
----
f(42, 'a string'); // Both 1st and 2nd parameters are non compliant
----
== How to fix it
Identify the scenario leading to the assignment of a value to a variable of type `void` and correct it:
* if the type of the variable is not known, declare it as `dynamic`
* if the type of the variable was mistakenly declared as `void`, replace it with the correct type
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
void x;
x = 3; // Non compliant
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
dynamic x; // type of x not known
x = 3;
----
==== Noncompliant code example
[source,dart,diff-id=2,diff-type=noncompliant]
----
void x;
x = 3; // Non compliant
----
==== Compliant solution
[source,dart,diff-id=2,diff-type=compliant]
----
int x; // void mistakenly used instead of the actual type