2016-07-26 63 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'方法中最普遍的方法 –