繁体   English   中英

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

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

我正在尝试发送一个条件语句(尚未评估)作为方法的参数。 我理解在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" );
      } 
  }

我尝试了很多这种设置的变化。 我每次都得到不同的错误:)

您几乎就在那里,您可以更改您的签名以接收BooleanSupplier ,它仅在调用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;
        }
    }
}

如果在调试模式下查看此示例,您将看到仅在执行condition.getAsBoolean()时才计算条件a != null && a.get()

将此应用于您的示例,您只需要更改

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" );

会正确编译(注意我删除了不必要的括号)。

暂无
暂无

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

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