天天看點

JDK将新增局部變量類型推斷功能

OpenJDK 提出一個新的計劃, 準備為 Java 增加局部變量類型推斷功能(local-variable type inference capability), 這讓代碼編寫更簡單, 同時也保證原有的靜态類型安全特性。

該計劃于3月8号提出,文檔位址為: JEP-286(JDK Enhancement Proposal,JDK增強方案)。 目前沒有指定具體在哪個JDK版本中實作。

提案中說:

“We seek to improve the developer experience by reducing the ceremony associated with writing Java code while maintaining Java’s commitment to static type safety by allowing developers to elide the often-unnecessary manifest declaration of local variable types, (我們緻力于改善編碼體驗, 減少非必要的代碼量,同時保持Java靜态類型安全的承諾,允許開發者省略不必要的類型聲明).”

其他靜态類型語言, 如 C++, Scala, 和 Go,都已經實作了局部變量類型推斷。

JEP 中強調:

“Java is nearly the only popular statically typed language that has not embraced local-variable type inference,( Java應該是最流行的幾種靜态類型語言中, 唯一不支援局部變量類型推斷的). ”

“At this point, this should no longer be a controversial feature.(在這一點上,應該不會有太多争議).”

Java開發人員經常會發現标準樣闆代碼體積臃腫。

“Manifest type declarations for locals are often perceived to be unnecessary or even in the way; given good variable naming, it is often perfectly clear what’s going on, (本地變量的類型清單通常來說是非必須的,指定一個有意義的變量名比什麼都好).”

JEP中寫到。

“The need to provide a manifest type for every variable also accidentally encourages developers toward overly complex expressions; with a lower-ceremony declaration syntax, there is less disincentive to break complex chained or nested expressions into simpler ones.(為每個變量指定類型也可能會導緻寫出很複雜的語句, 簡化文法聲明, 可以有效減少複雜的鍊式調用, 将嵌套表達式分解為簡單語句。)”

該計劃限制了類型推斷的使用場景: 有初始值的局部變量, 增強型for循環中的index, 普通for循環裡的局部變量。

“Quantitatively, we want that a substantial percentage of local variable declarations in real code bases can be converted using this feature, inferring an appropriate type.(在數量上, 我們希望可以根據這個特性,将絕大部分的局部變量, 推導出一個适當的類型聲明。)”

OpenJDK作為Java SE 的開源實作, 由Oracle提供支援。JavaSE 9 是Oracle官方的下一代版本,即将在一年以内釋出。JEP-286由Oracle的 Java平台組(Java platform group)首席架構師 Mark Reinhold 背書。

歡迎加入: CNC開源元件交流群 316630025

原文連結: http://www.javaworld.com/article/3044554/java-language/openjdk-plan-would-make-java-coding-easier.html

原文日期: 2016年03月15日

翻譯日期: 2016年03月17日

翻譯人員: 鐵錨 http://blog.csdn.net/renfufei