简体   繁体   English

如何使用lambda表达式向一个方法发送一个条件,以便它还没有被评估?

[英]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). 我理解在java8中lambda表达式是这样做的(有效地将条件放在函数中,并发送函数)。

// 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 :) 我每次都得到不同的错误:)

You were almost there, you can change your signature to receive a BooleanSupplier which will evaluate the condition only when calling getAsBoolean . 您几乎就在那里,您可以更改您的签名以接收BooleanSupplier ,它仅在调用getAsBoolean时评估条件。

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(BooleanSupplier condition) {
        condition.getAsBoolean();
    }

    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.getAsBoolean() is executed. 如果在调试模式下查看此示例,您将看到仅在执行condition.getAsBoolean()时才计算条件a != null && a.get()

Applying this to your example, you would only need to change 将此应用于您的示例,您只需要更改

void do_assertions( boolean argb , String args )

for 对于

void do_assertions(BooleanSupplier argo_supplier , String args )

and then call argo_supplier.getAsBoolean() where you want to evaluate the condition (after checking pvb_debuggable ). 然后调用argo_supplier.getAsBoolean()来评估条件(在检查pvb_debuggable )。

Then your line 然后你的线

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

would compile properly (notice that I removed the unnecessary brackets). 会正确编译(注意我删除了不必要的括号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM