【发布时间】:2014-06-16 09:36:44
【问题描述】:
我在编写一些 Java 代码时遇到了编译失败,我将其提炼为以下测试用例:
import java.util.Collections;
import java.util.List;
public class TernaryFailure {
public static List<String> thisWorks() {
return Collections.emptyList();
}
public static List<String> thisFailsToCompile() {
return true ? Collections.emptyList() : Collections.emptyList();
}
}
上面的代码使用 JDK 1.7.0_45 编译 javac 失败:
$ javac TernaryFailure.java TernaryFailure.java:10: error: incompatible types return true ? Collections.emptyList() : Collections.emptyList(); ^ required: List<String> found: List<Object> 1 error
但是,它使用 JDK 1.8.0_05 编译时没有任何错误。
这是 Java 7 实现中的错误吗?或者是否对 Java 8 中的 Java 语言规范进行了增强以开始允许这样做——如果是,有什么变化?
【问题讨论】:
-
三元运算符与通用返回一起存在问题,这是众所周知的。明确指定类型参数。
标签: java generics java-7 java-8 ternary-operator