Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread an array into multiple arguments for a function

How can I pass an array as three arguments to a function in Java? (Forgive me, I'm very new to Java).

I have the following function which takes float r, float g, float b, float a as arguments.

renderer.prepare(r, g, b, 1);

And I want to pass the output from this function in. (Or figure out how to return three separate unpacked floats).

public static float[] rgbToFloat(int r, int g, int b) {
    return new float[] {(float) r / 255f, (float) g / 255f, (float) b / 255f};
}

How can I do this? In some other languages it would look something like this:

renderer.prepare(...rgbToFloat(25, 60, 245), 1); 
like image 422
Jacob Birkett Avatar asked Jul 01 '17 19:07

Jacob Birkett


1 Answers

This is a typical example of an "X-Y Problem". Your original quest was to somehow group the 3 different parameters that you want to pass to a function. That's "problem X". Then you came up with the idea of using an array for this, but you were still unsure how to go about it, so you posted this question asking how to best use an array to achieve what you want. But that's "problem Y", not "problem X".

Using an array may and may not be the right way of solving "problem X". (Spoiler: it isn't.)

Honoring the principle of the least surprise, the best way of solving your problem "X" in my opinion is by declaring a new class, FloatRgba which encapsulates the four floats in individual float members: final float r; final float g; final float b; final float a;.

So, then your rgbToFloat() method does not have to return an unidentified array of float, instead it becomes a static factory method of FloatRgba:

public static FloatRgba fromIntRgb( int r, int g, int b ) 
{
    return new FloatRgba( r / 255f, g / 255f, b / 255f, 1.0f );
}

Finally, you introduce a utility function prepareRenderer which accepts a Renderer and a FloatRgba and invokes renderer.prepare(float, float, float, float) passing it the individual members of FloatRgba.

This way you keep everything clear, self-documenting, and strongly typed. Yes, it is a bit inconveniently verbose, but that's java for you.

like image 63
Mike Nakis Avatar answered Oct 04 '22 11:10

Mike Nakis