Java - lambda 推断类型
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
(String
传递给 ifNotNull
)和 B
(Integer
由 parseInt
) 当我执行以下操作时:
Integer i = ((Do) Integer::parseInt).ifNotNull(str);
这导致:
incompatible types: invalid method reference
对于你原来的问题,Optional 足以处理可为 null 的值
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
不匹配这个接口。
我正在尝试使用 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
(String
传递给 ifNotNull
)和 B
(Integer
由 parseInt
) 当我执行以下操作时:
Integer i = ((Do) Integer::parseInt).ifNotNull(str);
这导致:
incompatible types: invalid method reference
对于你原来的问题,Optional 足以处理可为 null 的值
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
不匹配这个接口。