2015-04-02 65 views
5

我想知道爲什麼在Java8 API的可選類有方法ifPresent(Consumer< T> consumer)而不是ifNotPresent(Runnable** consumer)Java可選爲什麼不是一個ifNotPresent方法?

API的意圖是什麼?它不是模仿功能模式匹配嗎?

** Java沒有零參數無效功能接口...

+3

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html – 2015-04-02 23:15:05

+1

這是因爲在計算應無副作用,所以如果我需要在執行的東西計算失敗,在不失敗的情況下,我不會對結果做任何事情,但會失去它......好了,現在很清楚,謝謝! – rascio 2015-04-02 23:25:34

+7

'.ifPresentOrElse'正在處理jdk9:[參見郵件列表討論](http://mail.openjdk.java.net/pipermail/core-libs-dev/2015-February/031223.html) – Misha 2015-04-02 23:44:18

回答

9

正如米沙說,這個功能will come with jdk9ifPresentOrElse方法的形式。

/** 
* 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(); 
    } 
} 
相關問題