您的方法声明返回类型是String.任何return语句都必须生成一个与声明的返回类型兼容的表达式.
但是,在这种情况下,返回类型可以是int,这解释了编译器拒绝它的原因.
这不是特定于三元运算符的,它也可以使用等效的if / else块进行复制:
if(distance < 1000)
return "train"; //This part is valid
else
return 10; //This line will be rejected by the compiler
出于同样的原因,最后一行将无法编译.这只是因为基本的类型检查.
System.out.println(distance < 1000 ? “train” : 10); compiles and runs without a problem.
这是因为编译器检测到String和int的公共类型,即Object,并解析为选择此签名:
java.io.PrintStream#println(Object x) // available in the target class
但是,这不适用于方法返回类型.
如果将返回类型更改为Object,则代码也会编译.但那当然不是你想要做的.
Ternary operations require both right-hand expressions to be of compatible data types
– >这部分实际上是有效的.这是解释它的方法:两个表达式中的每一个必须是单独兼容的:
String value = distance > 1000 ?
"train" //this must be compatible with String
:
10 //this too must be compatible with String (it isn't)
相反:
Object value = distance > 1000 ?
"train" //this must be compatible with Object (it is)
:
10 //this too must be compatible with Object (it is)
换句话说,对System.out.println的调用(距离< 1000?“train”:10)类似于上面的最后一个例子,其中期望的类型与两个表达式兼容.