2016-07-26 77 views
3

我正在玩弄FunctionalInterface的使用。我已經看到下面的代碼隨處可見的多種變化:Java - lambda推斷類型

int i = str != null ? Integer.parseInt() : null; 

我在尋找以下行爲:

int i = Optional.of(str).ifPresent(Integer::parseInt); 

ifPresent只接受SupplierOptional不能擴展。

我創建了以下FunctionalInterface

@FunctionalInterface 
interface Do<A, B> { 

    default B ifNotNull(A a) { 
     return Optional.of(a).isPresent() ? perform(a) : null; 
    } 

    B perform(A a); 
} 

這讓我做到這一點:

Integer i = ((Do<String, Integer>) Integer::parseInt).ifNotNull(str); 

可以添加多個默認的方法做這樣的事情

LocalDateTime date = (Do<String, LocalDateTime> MyDateUtils::toDate).ifValidDate(dateStr); 

而且它很好地讀取Do [my function] and return [function return value] if [my condition] holds true for [my input], otherwise null

爲什麼不能編譯器推斷類型的AString傳遞給ifNotNull)和B(由parseInt返回Integer),當我做到以下幾點:

Integer i = ((Do) Integer::parseInt).ifNotNull(str); 

這導致:

不兼容類型:無效方法參考

回答

9

對於您原來的問題可選功能強大,足以應付空的值

Integer i = Optional.ofNullable(str).map(Integer::parseInt).orElse(null); 

對於日期例如,它看起來像

Date date = Optional.ofNullable(str).filter(MyDateUtils::isValidDate).map(MyDateUtils::toDate).orElse(null); 

關於類型的錯誤

Integer i = ((Do<String, Integer>) Integer::parseInt).ifNotNull(str); 

指定通用Do接口的參數解決了一個問題。問題是沒有指定類型參數的Do意味着Do<Object, Object>Integer::parseInt與此接口不匹配。

+0

好啊,我沒有意識到'Optional'的'map'功能。謝謝! – Ian2thedv

+0

很高興幫助。看看'Optional#flatMap'是'Optional'方法中最普遍的方法 –