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

I am trying to send a condition statement (which has not yet been evaluated) as an argument to a method. I understand that in java8 , a lambda expression is a way to do this (effectively putting a condition inside a function and sending a 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 setting. I get different errors every time :)

+4
source share
1 answer

You were almost there, you can change your signature to get a BooleanSupplier , which will evaluate the condition only when called getAsBoolean.

:

public class Test {

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

    static void test(BooleanSupplier condition) {
        condition.getAsBoolean();
    }

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

, , a != null && a.get() condition.getAsBoolean().

,

void do_assertions( boolean argb , String args )

void do_assertions(BooleanSupplier argo_supplier , String args )

argo_supplier.getAsBoolean(), ( pvb_debuggable).

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

( , ).

+6

All Articles