File: FunctionalInterfaceMethodChanged.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 (37 lines) | stat: -rw-r--r-- 1,184 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
There are only two correct ways to have one [`@FunctionalInterface`] extend
another [`@FunctionalInterface`]—the way where you leave the abstract method
alone, and the way where you make a different abstract method but a default
method for the original abstract method simply delegates to the new name.

If you do anything else, you create a situation where what looks like a "cast"
actually changes behavior. That is really quite bad for understandability.

For example, if the method `bar()` changes the behaviour of `qux()`, then the
same lambda cast to `A` or `B` could have completely different behaviour.

```java
@FunctionalInterface
interface A {
  Foo bar();
}

@FunctionalInterface
interface B extends A {
  Foo qux();
  @Override
  default Foo bar() {
    // anything here but exactly `return qux();` or perhaps `return (SomeType) qux();`
  }
}
```

If you need to change the behaviour of an existing lambda, prefer an explicit
decorator method, e.g.:

```java
static Runnable crashTerminating(Runnable r) {
  return () -> { ...wrapping behavior goes here... }
}
```

[`@FunctionalInterface`]: https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html