PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 28, 2022

[FIXED] How to fix SonarLint: Refactor this code to use the more specialised Functional Interface 'BinaryOperator<Float>'?

 April 28, 2022     java, lambda, sonarlint, sonarlint-intellij, warnings     No comments   

Issue

So im learning on how to use Lambda in Java and got the problem, that Sonar Lint is saying i should refactor the code to use the more specialised functional interface.

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);
  }

All this little program should do is calculate the average of the two floats. The programm's working fine, but I want the warning to be gone. So how can I avoid that waring and fix the code?

Edit: I oc tried finding a solution on google etc., but found none.


Solution

The BinaryOperator<T> is in fact a subinterface of BiFunction<T, T, T>, and its documentation states "this is a specialization of BiFunction for the case where the operands and the result are all of the same type", so just replace with:

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

Also no need to declare the Float argument types, it is auto-inferred by the compiler:

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


Answered By - M A
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing