简体   繁体   English

Java 7钻石运营商:为什么难以实施?

[英]Java 7 diamond operator: why was it difficult to implement?

I watched the Oracle OTN Virtual Event: Java SE and JavaFX 2.0 (28 Feb 2012) and while talking about the new diamond operator (that Map<String, List<String>> myMap = new HashMap<>(); thing) the speaker mentioned that it was not as simpleto implement than one might think, as it is not a simple token replacement. 我观看了Oracle OTN虚拟事件:Java SE和JavaFX 2。0(2012年2月28日),同时讨论了新的菱形运算符( Map<String, List<String>> myMap = new HashMap<>(); thing)提到它并不像人们想象的那么简单,因为它不是一个简单的令牌替代品。

My question is why? 我的问题是为什么? Why can't be this implemented as simply taking the string from the variable's declaration and put it into the diamond operator? 为什么不能简单地从变量声明中取出字符串并将其放入菱形运算符中?

I didn't implement it either, so I can only guess. 我也没有实现它,所以我只能猜测。

But usually the reason these things are more complex than they seem is that first inspection only looks at the most common (or most publicized) use case. 通常这些事情比它们看起来更复杂的原因是第一次检查只关注最常见(或最公开)的用例。 In this case it's the one you mentioned. 在这种情况下,它是你提到的那个。 In theory that should be easy to specify exactly and it should be rather easy to implement in a compiler. 从理论上讲,它应该很容易准确指定,并且应该很容易在编译器中实现。

However, the diamond operator (which is not technically a operator, by the way) can be used in different ways as well: 然而,钻石操作员(顺便说一下,在技术上不是操作员)也可以以不同的方式使用:

someMethodWithGenericArguments(new HashMap<>());
new SomeGenericClass(new HashMap<>());
T foo = new SomethingRelatedToT<>(); // where T is a generic type parameter

In those cases a simple token replacement obviously no longer works, you need actual type inference involving real type analysis (ie it's on an entirely different abstraction level as a simple token replacement would be). 在这些情况下,简单的令牌替换显然不再有效,您需要涉及实际类型分析的实际类型推断(即,它在完全不同的抽象级别上作为简单的令牌替换将是)。

Something which Java doesn't do (which many languages have) is implied types based on usage. Java没有做的事情(许多语言都有)是基于用法的隐含类型。 ie Java doesn't imply a require type based on how it is used. 即Java并不暗示基于其使用方式的require类型。

eg 例如

 Type a = b;

The type of a and the type of b are independent and no assumptions are made about b based on the type of a . 该类型的a的类型和b是独立的,没有假设关于由b根据类型a

MethodHandles are showing signs of supporting this. MethodHandles显示出支持这一点的迹象。 The return type use can be based on context, but this is a runtime feature. 返回类型的使用可以基于上下文,但这是一个运行时功能。

In conclusion, my assumption is; 总之,我的假设是; It was hard to implement in Java because the language didn't support any like it. 在Java中很难实现,因为语言不支持任何类似的语言。 If the language used feature like this all the time, the approach to take would be understood (in term of defining a spec of how it should work) and supported by the tools in the compiler. 如果所使用的语言一直都是这样的特征,那么可以理解采用的方法(在定义它应该如何工作的规范方面)并且由编译器中的工具支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM