簡體   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