I have this function a:
public void a(BooleanSupplier param){}
that is called by function b:
public void b(Boolean param){
a(param)
}
The problem is that function "a" is expecting a BooleanSupplier but function b is sending a Boolean. I think I should convert a Boolean into a BooleanSupplier but I could not manage to convert one to another. Any help is appreciated :)
CodePudding user response:
Let us take a closer look at the BooleanSupplier
-interface. This is a functional interface, i.e. it has only one abstract method boolean getAsBoolean()
. As we can see, the method has no parameters and returns a boolean
.
Now let us look at the code presented. Method b
receives one parameter Boolean param
. method a
receives one parameter of type BooleanSupplier
. How can we convert the Boolean
received by b
to a BooleanSupplier
? We just need to create a lambda that - when called - returns param
. When written as lambda, this looks as follows:
only expression in the lambda -> return-value
^
|
() -> param;
|
v
empty parameter list
The minor type mismatch between Boolean
(type of param
) and boolean
(expected return-type of BooleanSupplier
) is resolved through autoboxing (oracle.com
).
So in total, we can now call a
as follows:
a(() -> param);
For further information on lambdas and their syntax, I recommend reading a tutorial on the topic, e.g. this one from oracle.com
.