Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert from Boolean to BooleanSupplier

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading