error-prone icon indicating copy to clipboard operation
error-prone copied to clipboard

`UnusedVariable` behaves inconsistently for method references and equivalent lambda expressions.

Open Emilyaxe opened this issue 7 months ago • 1 comments

Error Prone version

2.49.0 (error_prone_core)

Description

UnusedVariable behaves inconsistently for method references and equivalent lambda expressions. When transform(String name) is called via this::transform, Error Prone does not report name as unused. After rewriting the call site to n -> transform(n), the same parameter is flagged. Since the method body is unchanged and name is never used, the method-reference case is a false negative.

Reproducer

package demo;

import java.util.List;
import java.util.stream.Collectors;

public class TypeParameterMethodRef<T> {

    // BEFORE: no UnusedVariable warning on `name`
    public List<List<T>> processRef(List<String> names) {
        return names.stream()
            .map(this::transform)
            .collect(Collectors.toList());
    }

    // AFTER: UnusedVariable reported on `name`
    public List<List<T>> processLambda(List<String> names) {
        return names.stream()
            .map(n -> transform(n))
            .collect(Collectors.toList());
    }

    private List<T> transform(String name) {
        throw new UnsupportedOperationException("transform not implemented");
    }
}

Actual behavior

UnusedVariable is reported only when transform is called from a lambda; the method-reference call site suppresses the warning for the same unused parameter.

Emilyaxe avatar Apr 30 '26 08:04 Emilyaxe

Fixed in commit 53350e7.

The root cause was in FilterUsedVariables.visitMemberReference — when encountering a method reference like this::transform, the code was calling symbol.getParameters().forEach(unusedElements::remove), which removed the referenced method's parameters from tracking entirely, treating them as "used" regardless of whether they actually were. There was no equivalent suppression for the lambda case, which is why the two forms behaved differently.

The fix removes that suppression so parameters are tracked normally in both cases. I also guarded the suggested-fix generation to not propose removing the parameter when the method is used as a method reference, since doing so would break the signature match with the functional interface.

AboodFares avatar May 12 '26 15:05 AboodFares