[英]Local Variable Type Inference with Conditional (Ternary) Operator of Different Types
var test = "Hello World!";
In Java 10+, the above snippet compiles, and test
is inferred to be a String
at compile-time. 在Java 10+中,上面的代码片段编译,并且在编译时
test
被推断为String
。
However, we can use the conditional (ternary) operator to return different types, such as: 但是,我们可以使用条件(三元)运算符返回不同的类型,例如:
var test = new Random().nextBoolean() ? "Hello World!" : 123;
If we were to print test.getClass()
at runtime, it would output either: 如果我们在运行时打印
test.getClass()
,它将输出:
- class java.lang.String
class java.lang.String
- class java.lang.Integer
class java.lang.Integer
This makes sense, but what would the type of test
be at compile-time? 这是有道理的,但是在编译时
test
的类型是什么? Would it be Object
, or something else? 它会是
Object
还是其他什么?
Interestingly, Intellij tells me that the type of test
is not Object
, but rather this beast: 有趣的是,Intellij告诉我,
test
的类型不是Object
,而是这个野兽:
java.io.Serializable & Comparable<? extends java.io.Serializable & Comparable<?> & constant.Constable & constant.ConstantDesc> & constant.Constable & constant.ConstantDesc
The reason why this is the case is because the compiler infers the type of the variable to be the closest common superclasses between String
and Integer
, which are in-fact Serializable
, Comparable
, Constable
, and ConstantDesc
in Java 12. 这种情况的原因是因为编译器将变量的类型推断为
String
和Integer
之间最接近的公共超类,它们实际上是Java 12中的Serializable
, Comparable
, Constable
和ConstantDesc
。
There's an interesting article that elaborates on impossible types , which are what these types are known as (since they can only be inferred by the compiler): Representing the Impractical and Impossible with JDK 10 “var” 有一篇有趣的文章详细阐述了不可能的类型 ,这些类型被称为(因为它们只能由编译器推断): 用JDK 10“var”代表不切实际和不可能的类型
If we were to return objects that are entirely unrelated, such as Integer
and ByteArrayOutputStream
, then we would see that Java would infer the compile-time type of test
to be Object
: 如果我们要返回完全不相关的对象,例如
Integer
和ByteArrayOutputStream
,那么我们会看到Java会将编译时类型的test
推断为Object
:
var test = new Random().nextBoolean() ? 123 : new ByteArrayOutputStream();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.