繁体   English   中英

Java - lambda推断类型

[英]Java - lambda infer type

我正在使用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

当我执行以下操作时,为什么编译器无法推断A (传递给ifNotNull String )和B (由parseInt返回的Integer )的类型:

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

这导致:

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

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

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不符合这个接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM