Java - lambda推断类型

Ian*_*edv 3 java lambda functional-interface

我正在玩a的用法FunctionalInterface.我到处都看到了以下代码的多种变体:

int i = str != null ? Integer.parseInt() : null;
Run Code Online (Sandbox Code Playgroud)

我正在寻找以下行为:

int i = Optional.of(str).ifPresent(Integer::parseInt);
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

这允许我这样做:

Integer i = ((Do<String, Integer>) Integer::parseInt).ifNotNull(str);
Run Code Online (Sandbox Code Playgroud)

可以添加更多默认方法来执行诸如此类操作

LocalDateTime date = (Do<String, LocalDateTime> MyDateUtils::toDate).ifValidDate(dateStr);
Run Code Online (Sandbox Code Playgroud)

它读得很好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);
Run Code Online (Sandbox Code Playgroud)

这导致:

不兼容的类型:无效的方法引用

Naz*_*iuk 9

对于您的原始问题可选功能足以处理可空值

Integer i = Optional.ofNullable(str).map(Integer::parseInt).orElse(null);
Run Code Online (Sandbox Code Playgroud)

对于日期示例,它看起来像

Date date = Optional.ofNullable(str).filter(MyDateUtils::isValidDate).map(MyDateUtils::toDate).orElse(null);
Run Code Online (Sandbox Code Playgroud)

关于类型错误

Integer i = ((Do<String, Integer>) Integer::parseInt).ifNotNull(str);
Run Code Online (Sandbox Code Playgroud)

Do接口指定通用参数可以解决问题.问题是,只是Do没有指定类型的参数是指Do<Object, Object>Integer::parseInt不符合此接口.