Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid @UnnecessaryLambda patch suggestion #2518

Closed
Stephan202 opened this issue Aug 25, 2021 · 1 comment
Closed

Invalid @UnnecessaryLambda patch suggestion #2518

Stephan202 opened this issue Aug 25, 2021 · 1 comment

Comments

@Stephan202
Copy link
Contributor

Consider the following code:

import java.util.stream.IntStream;

class Example {
  void someLoopyCode() {
    for (int i : someIterable()) {
      // Do something.
    }
  }

  private Iterable<Integer> someIterable() {
    return () -> IntStream.range(0, 42).boxed().iterator();
  }
}

Compile the code as follows:

javac \
  -XDcompilePolicy=simple \
  -processorpath error_prone_core-2.9.0-with-dependencies.jar \
  '-Xplugin:ErrorProne -XepDisableAllChecks -Xep:UnnecessaryLambda:WARN' \
  Example.java

This yields the following warning:

Example.java:10: warning: [UnnecessaryLambda] Returning a lambda from a helper method or saving it in a constant is unnecessary; prefer to implement the functional interface method directly and use a method reference instead.
  private Iterable<Integer> someIterable() {
                            ^
    (see https://errorprone.info/bugpattern/UnnecessaryLambda)
  Did you mean 'for (int i : this::someIterable) {'?
1 warning

If this suggestion were accepted using -XepPatchChecks:UnnecessaryLambda the resulting code would not compile, producing a "method reference not expected here" error. Possible solutions:

  1. Don't flag enhanced for-loop method calls.
  2. Introduce an explicit cast (i.e., suggest for (int i : (Iterable<Integer>) this::someIterable) { instead).
jingjing-0919 added a commit to jingjing-0919/error-prone that referenced this issue May 29, 2022
copybara-service bot pushed a commit that referenced this issue Sep 15, 2023
copybara-service bot pushed a commit that referenced this issue Sep 15, 2023
copybara-service bot pushed a commit that referenced this issue Sep 15, 2023
copybara-service bot pushed a commit that referenced this issue Sep 15, 2023
@cushon
Copy link
Collaborator

cushon commented Sep 15, 2023

93ca62e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants