3
我正在玩弄FunctionalInterface
的使用。我已经看到下面的代码随处可见的多种变化:Java - lambda推断类型
int i = str != null ? Integer.parseInt() : null;
我在寻找以下行为:
int i = Optional.of(str).ifPresent(Integer::parseInt);
但ifPresent
只接受Supplier
和Optional
不能扩展。
我创建了以下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
。
为什么不能编译器推断类型的A
(String
传递给ifNotNull
)和B
(由parseInt
返回Integer
),当我做到以下几点:
Integer i = ((Do) Integer::parseInt).ifNotNull(str);
这导致:
不兼容类型:无效方法参考
好啊,我没有意识到'Optional'的'map'功能。谢谢! – Ian2thedv
很高兴帮助。看看'Optional#flatMap'是'Optional'方法中最普遍的方法 –