如何修复 SonarLint:重构此代码以使用更专业的功能接口"二进制运算符<Float>"?



因此,我正在学习如何在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);
}

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

编辑:我曾尝试在谷歌等网站上找到解决方案,但没有找到。

BinaryOperator<T>实际上是BiFunction<T, T, T>的子接口,其文档状态为"这是BiFunction对于操作数和结果都是相同类型的情况的特殊化,所以只需替换为:

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

同样不需要声明Float参数类型,它是由编译器自动推断的:

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

最新更新