2015-04-02 26 views
5

Java8 API'sında Optional sınıfının nedenve ifNotPresent(Runnable** consumer) yöntemine sahip olduğunu merak ediyordum?Java İsteğe bağlı neden bir ifNotPresent yöntemi değil?

API'nin amacı nedir? Fonksiyonel desen uyumu taklit etmek değil mi?

** Java sıfır argüman geçersiz fonksiyonel bir arayüze sahip değil ...

+3

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html –

+1

ne zaman bir şey yürütmek gerekirse böylece hesaplama, yan etki özgür olmalıdır, çünkü öyle hesaplama başarısız, başarısız olursa, sonuçla hiçbir şey yapmayacağım, ama kaybedeceğim ... tamam şimdi açık, teşekkürler! – rascio

+7

'.ifPresentOrElse' jdk9 için boru hattında: [posta listesi tartışmasına bakın] (http://mail.openjdk.java.net/pipermail/core-libs-dev/2015-February/031223.html) – Misha

cevap

9

Misha söylediği gibi, bir ifPresentOrElse yöntemi şeklinde bu özellik will come with jdk9.

/** 
* 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(); 
    } 
} 
İlgili konular