-1

I have a working method that uses parameter as a lambda expression

private BiConsumer<List<String>, Properties> handleList(Properties p) {
    return (list, prop) -> executeSubList(list, prop);
}

For p I'm getting a false positive warning from SonarLint

Unused method parameters should be removed (squid:S1172)

If I change prop to p I'm getting a compile error

Lambda expression's parameter p cannot redeclare another local variable defined in an enclosing scope

Is there a real issue or is it a false positive check when using a method parameter as a lambda parameter?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ori Marko
  • 56,308
  • 23
  • 131
  • 233

2 Answers2

5

The issue is real. This method returns a BiConsumer that runs executeSubList on a pair or List<String> and Properties arguments, but does so regardless of p. You could just remove it:

private BiConsumer<List<String>, Properties> handleList() {
    // p was never used, and can just be removed -------^
    return (list, prop) -> executeSubList(list, prop);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Good catch, the issue is real - but it is another one than stated (should be "unused parameter"). – daniu Mar 30 '20 at 07:17
  • @user7294900 A `BiConsumer` consumes two things, hence the name. So the method returns you an object that can be used to consume a `List` and a `Properties`. So `BiConsumer consumer = handleList();` and then `consumer.accept(myList, myProperties);`. – Zabuzard Mar 30 '20 at 07:22
3

The accepted answer is totally correct.

However, another take on solving this problem is to create a Consumer instead of a BiConsumer. The parameter p would then be used as the parameter to executeSubList():

private Consumer<List<String>> handleList(Properties p) {
  return (list) -> executeSubList(list, p);
}

Whether this or the solution provided in the accepted answer is the best way to go is dependant on how the surrounding code looks and how the method is to be used.

Magnilex
  • 11,584
  • 9
  • 62
  • 84