rspec/rules/S7061/dart/rule.adoc
github-actions[bot] a769db8a39
Create rule S7061: Implicit tearoff of "call" shouldn't be used (#4226)
Co-authored-by: leveretka <leveretka@users.noreply.github.com>
2024-09-09 09:55:51 +02:00

79 lines
1.9 KiB
Plaintext

== Why is this an issue?
In Dart instances of a class could be treated as functions. To achieve this, the class should implement a `call` method. This example illustrates the usage of this language feature:
[source,dart]
----
class F {
void call() {}
}
void g(void Function() f) {
f();
}
g(F()); // Here an instance of F is passed where the Function is expected
----
While this implicit tear off looks very concise, it has a serious drawback. This implicit conversion might happen accidentally, if you just happen to have a `call` method and by mistake passed an instance as a `Function`. Moreover, such code is much harder to read and understand as you don't see any difference, between being passed as an object or as a function. Taking this all into account, this behavior could be removed in the next versions of the language. Thus, to avoid confusion and potential compatibility problem, this is highly recommended to make the passing of a `call()` method explicit.
== How to fix it
Pass `instance.call` instead of `instance`, where the `Function` is expected.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
class F {
void call() {}
}
void g(void Function() f) {
f();
}
g(F());
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
class F {
void call() {}
}
void g(void Function() f) {
f();
}
g(F().call);
----
== Resources
=== Documentation
* Dart Docs - https://dart.dev/tools/linter-rules/implicit_call_tearoffs[Dart Linter rule - implicit_call_tearoffs]
* Dart Docs - https://dart.dev/language/callable-objects[Callable objects]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Implicit tear-off of the 'call' method.
=== Highlighting
Cascade expression
'''
== Comments And Links
(visible only on this page)
endif::env-github,rspecator-view[]