Friday, November 4, 2022

[FIXED] How to pass an Array as a parameter to a Function/Bifunction?

Issue

I need to pass an array as parameter into a BiFunction.

Use case :

Calculate the Euclidean Distance of 2 coordinates given in an array. coordinate1 and coordinate2 are an array.

The below trial, makes the intent clearer.

BiFunction<Integer, Integer, Double> euclideanDistance =
   (Integer[] x, Integer[] y) -> Math.sqrt(Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2));

But the compiler complains :

incompatible types:
incompatible parameter types in lambda expression :
Expected Integer but found Integer[]

Solution

You can use any reference type as a parameter to the Function. Your BiFunction should take two int[] as it's input and return a Double. So, the target type of the assignment should be something like this.

BiFunction<int[], int[], Double> euclideanDistance =
                (int[] x, int[] y) -> Math.sqrt(Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2));


Answered By - Ravindra Ranwala
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

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