【发布时间】:2017-11-16 19:45:11
【问题描述】:
代码不应该编译,但它可以!
public class MyClass {
...........
private void setEndDateOfValidStatusToCurrentTime(List<LifecycleStatus> oldStatuses, Date currentTime)
{
oldStatuses.stream()
.filter(oldStatus -> isValidNow(oldStatus, currentTime))
.findFirst().ifPresent(oldStatus -> oldStatus.setValidToDate(currentTime));
}
private boolean isValidNow(LifecycleStatus lifecycleStatus, Date currentTime)
{
Date start = lifecycleStatus.getValidFromDate();
Date end = lifecycleStatus.getValidToDate();
Date startTime = Optional.ofNullable(start).orElse(new Date(0L)); // BEGINNING OF TIME
Date endTime = Optional.ofNullable(end).orElse(new Date(Long.MAX_VALUE)); // END OF TIME
return startTime.before(currentTime) && endTime.after(currentTime);
}
}
原因: 我在 lambda 中使用 isValidNow() 来定位 Predicate 接口,因为过滤器方法需要它。但是 isValidNow() 是一个 2 参数方法,而 Predicate 中的 test() 只需要 1 个参数!
我知道 Java 编译器具有类型推断的能力。有了这样的能力,智能编译器可能会在内部分解 isValidNow(),确定它可以安全地搁置第二个参数 (currentTime),并通过仅使用第一个参数 (oldStatus) 来提供满足 Predicate 中的 test() 的实现.
那么当我尝试使用方法引用时,为什么类型推断不起作用呢?有趣的是,如果我替换
filter(oldStatus -> isValidNow(oldStatus, currentTime))
与
filter(this::isValidNow)
我看到了这些编译器错误:
- The method filter(Predicate<? super LifecycleStatus>) in the type Stream<LifecycleStatus> is not applicable for the arguments
(this::isValidNow)
- MyClass does not define isValidNow(LifecycleStatus) that is applicable here
【问题讨论】:
标签: java lambda type-inference method-reference