我想知道为什么在Java8 API上,Optional类有方法ifPresent(Consumer< T> consumer)
而不是ifNotPresent(Runnable** consumer)
?
API的目的是什么?是不是要模拟功能模式匹配?
** Java没有零参数void功能接口...
答案 0 :(得分:9)
正如Misha所说,此功能will come with jdk9采用ifPresentOrElse
方法的形式。
/**
* If a value is present, performs the given action with the value,
* otherwise performs the given empty-based action.
*
* @param action the action to be performed, if a value is present
* @param emptyAction the empty-based action to be performed, if no value is
* present
* @throws NullPointerException if a value is present and the given action
* is {@code null}, or no value is present and the given empty-based
* action is {@code null}.
* @since 9
*/
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
if (value != null) {
action.accept(value);
} else {
emptyAction.run();
}
}