Java - lambda推断类型

时间:2016-07-26 10:36:36

标签: java lambda functional-interface

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

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)和BInteger parseInt返回的类型Integer i = ((Do) Integer::parseInt).ifNotNull(str); })当我执行以下操作时:

{{1}}

这导致:

  

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

1 个答案:

答案 0 :(得分:9)

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

Integer i = ((Do<String, Integer>) Integer::parseInt).ifNotNull(str);

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

Do

关于类型错误

Do

Do<Object, Object>接口指定通用参数可以解决问题。问题是只有Integer::parseInt没有指定类型参数意味着^[1-9][0-9]{6}*${6}*与此接口不匹配。

相关问题