dsdsdsdsd dsdsdsdsd - 1 year ago 38
Java Question

How to send a condition to a method using lambda expression so that it is not yet evaluated?

I am trying send a condition statement (that has not been evaluated yet) as an argument to a method. I understand that in java8, the lambda expression is the way to do it (effectively putting the condition inside a function, and sending the function).

// simple method inside a utilities class
// that does assertions if global debug parameter is true

public class MyUtils
public static void do_assertions( boolean argb , String args )
if( BuildConfig.pvb_debuggable )
{ assert argb , args ;

// somewhere within app where a development-phase assertion is needed

public class some_class
public void some_method( )
EditText lvo_editText = (EditText) findViewById( "the_id" ) ;

//assert lvo_editText != null;
// ... replace this with a call to do_assertions
MyUtils.do_assertions( () -> { lvo_editText != null ; } , "bad EditText" );

I have tried many variations of this setup. I get different errors each time :)

Answer Source

You were almost there, you can change your signature to receive a Supplier of boolean which will evaluate the condition only when calling get.

Here a simple example :

public class Test {

    public static void main(String args[]) {
        A a = new A();
        test(() -> a != null && a.get());

    static void test(Supplier<Boolean> condition) {

    static class A {
        boolean get(){
            return true;

If you go through this example in debug mode, you'll see that the condition a != null && a.get() is evaluated only when condition.get() is executed.

Applying this to your example, you would only need to change

void do_assertions( boolean argb , String args )


void do_assertions(Supplier<Boolean> argo_supplier , String args )

and then call argo_supplier.get() where you want to evaluate the condition (after checking pvb_debuggable).

Then your line

MyUtils.do_assertions( () -> lvo_editText != null  , "bad EditText" );

would compile properly (notice that I removed the unnecessary brackets).