因此,我正在学习如何在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等上找到解决方案,但没有找到。
答案 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;