File: IncompatibleArgumentType.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (38 lines) | stat: -rw-r--r-- 1,602 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
The called method is annotated with `@CompatibleWith`, which enforces that the
parameter passed to the method can potentially be [cast][jls] to the appropriate
generic type. However, the type of the parameter passed can't be cast to the
appropriate generic type.

This is useful when a method can't just take a parameter of the generic type to
allow developers to safely operate with instances held with a wildcard type when
using an instance as both a _consumer_ and _producer_ of values. This should
_not_ be the default, as most interfaces are either one or the other. Containers
and container-like class are the most likely places to use this tool.

TIP: More explanation can be found on the page for [CollectionIncompatibleType]

```java
interface Container<T> {
  void add(T thing);
  boolean contains(@CompatibleWith("T") Object thing);
  boolean containsAsT(T thing);
}

void containmentCheck(Container<? extends Number> container) {
  container.contains(2); // OK, int can be cast to Number
  container.contains(2.0); // OK, double can be cast to Number
  container.contains("a"); // Not OK, String can't be cast to number

  // Does not compile, since, for example, container might be Container<Double>, and Integer
  // can't be cast to Double.
  container.containsAsT(2);

  Container<String> stringContainer = ...;
  stringContainer.contains("a"); // OK
  // OK, since Object *could* be cast to String
  stringContainer.contains(new Object() {});
}
```

[CollectionIncompatibleType]: CollectionIncompatibleType
[jls]: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.5.1