Java - lambda 推断类型

Java - lambda infer type

我正在尝试使用 FunctionalInterface。我到处都看到以下代码的多种变体:

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

为什么编译器不能推断出 AString 传递给 ifNotNull)和 BIntegerparseInt) 当我执行以下操作时:

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

这导致:

incompatible types: invalid method reference

对于你原来的问题,Optional 足以处理可为 null 的值

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 不匹配这个接口。