3

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

int i = str != null ? Integer.parseInt() : null;

我正在寻找以下行为:

int i = Optional.of(str).ifPresent(Integer::parseInt);

ifPresent只接受a 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);

这导致:

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

4

1 回答 1

9

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

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

于 2016-07-26T10:49:00.997 回答