我正在玩弄 a 的使用FunctionalInterface。我到处都看到了以下代码的多种变体:
int i = str != null ? Integer.parseInt() : null;
我正在寻找以下行为:
int i = Optional.of(str).ifPresent(Integer::parseInt);
但ifPresent只接受a 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(Integer返回)的类型:parseInt
Integer i = ((Do) Integer::parseInt).ifNotNull(str);
这导致:
不兼容的类型:无效的方法引用