![](/img/trans.png)
[英]Why can't Java infer the type of a lambda expression with a generic type parameter?
[英]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
。
当我执行以下操作时,为什么编译器无法推断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.