使用Runnable将处理程序升级为Lambda表达式

时间:2018-07-08 08:38:16

标签: java android lambda java-8

我想升级此代码以使用lambda表达式:

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        missileX = ufoX;
        resetRecent();
        waitForUfoTimer = false;
    }
}, randomize(20000, 18000));

我以此方式尝试,但无法编译:

Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(Runnable task = () -> {  
    missileX = ufoX;
    resetRecent();
    waitForUfoTimer = false; 
  }
}, randomize(20000, 18000));

哪里有一些说明,以便我可以学习如何做?我必须猜测语法是荒谬的。

1 个答案:

答案 0 :(得分:2)

您不必声明要分配给lambda的变量。足够了:

Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(() -> {  
    missileX = ufoX;
    resetRecent();
    waitForUfoTimer = false; 
  }
, randomize(20000, 18000));