且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Optional.ifPresent() 的正确使用

更新时间:2022-03-04 17:11:06

Optional.ifPresent() 需要一个 Consumer 作为参数.你传递给它一个类型为 void 的表达式.所以这不编译.

Optional<User>.ifPresent() takes a Consumer<? super User> as argument. You're passing it an expression whose type is void. So that doesn't compile.

消费者旨在实现为 lambda 表达式:

A Consumer is intended to be implemented as a lambda expression:

Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));

或者更简单,使用方法引用:

Or even simpler, using a method reference:

Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);

这和

Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
    @Override
    public void accept(User theUser) {
        doSomethingWithUser(theUser);
    }
});

这个想法是 doSomethingWithUser() 方法调用只会在用户存在时执行.您的代码直接执行方法调用,并尝试将其 void 结果传递给 ifPresent().

The idea is that the doSomethingWithUser() method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its void result to ifPresent().