如何修复SonarLint:重构此​​代码以使用更专门的功能接口'BinaryOperator <Float>'?

时间:2020-07-08 08:50:28

标签: java lambda warnings sonarlint sonarlint-intellij

因此,我正在学习如何在Java中使用Lambda并遇到问题,Sonar Lint表示我应该重构代码以使用更专业的功能接口。

public float durchschnitt(float zahl1, float zahl2) {
    BiFunction<Float, Float, Float> function = (Float ersteZahl, Float zweiteZahl) -> (ersteZahl + zweiteZahl) / 2;
//  ^
//  Here I get the warning:
//  SonarLint: Refactor this code to use the more specialised Functional Interface 'BinaryOperator<Float>'
    return function.apply(zahl1, zahl2);
  }

这个小程序应该做的就是计算两个浮点的平均值。程序运行正常,但我希望警告消失。那么如何避免这种警告并修复代码?

编辑: 我尝试在Google等上找到解决方案,但没有找到。

1 个答案:

答案 0 :(得分:3)

BinaryOperator<T>实际上是BiFunction<T, T, T>的子接口,并且它的documentation表示”“这是BiFunction的一种特殊形式,其中操作数和结果都是相同的类型” ,因此只需替换为:

BinaryOperator<Float> function = (Float ersteZahl, Float zweiteZahl) -> (ersteZahl + zweiteZahl) / 2;

也无需声明Float参数类型,它是由编译器自动推断的:

BinaryOperator<Float> function = (ersteZahl, zweiteZahl) -> (ersteZahl + zweiteZahl) / 2;