Java“?"用于检查 null 的运算符 - 它是什么?(不是三元!) [英] Java "?" Operator for checking null - What is it? (Not Ternary!)
问题描述
我正在阅读一篇从 slashdot 故事链接的文章,并发现了这个小花絮:
<块引用>采用最新版本的 Java,其中尝试进行空指针检查通过提供速记语法更容易用于无休止的指针测试.只是为每个方法添加一个问号调用自动包括一个测试空指针,替换一个if-then 语句的老鼠窝,例如作为:<代码><预>公共字符串getPostcode(人){字符串 ans=null;如果(人!= null){姓名 nm= person.getName();如果(纳米!= null){ans= nm.getPostcode();}}返回答案}
有了这个:<代码><预>公共字符串 getFirstName(Person 人) {return person?.getName()?.getGivenName();}
我搜索了互联网(好吧,我花了至少 15 分钟在谷歌上搜索java问号"的变体)却一无所获.所以,我的问题:是否有任何官方文件?我发现 C# 有一个类似的运算符(??"运算符),但我想获取我正在使用的语言的文档.或者,这只是我使用的三元运算符的使用从未见过.
谢谢!
文章链接:http://infoworld.com/d/developer-world/12-programming-mistakes-avoid-292
最初的想法来自 groovy.它被提议用于 Java 7 作为 Project Coin 的一部分:https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators),但还未被接受.
相关的 Elvis 运算符 ?: 被提议将 x ?: y
简写为 x != null ?x : y
,当 x 是一个复杂的表达式时特别有用.
I was reading an article linked from a slashdot story, and came across this little tidbit:
Take the latest version of Java, which tries to make null-pointer checking easier by offering shorthand syntax for the endless pointer testing. Just adding a question mark to each method invocation automatically includes a test for null pointers, replacing a rat's nest of if-then statements, such as:
public String getPostcode(Person person) { String ans= null; if (person != null) { Name nm= person.getName(); if (nm!= null) { ans= nm.getPostcode(); } } return ans }With this:
public String getFirstName(Person person) { return person?.getName()?.getGivenName(); }
I've scoured the internet (okay, I spent at least 15 minutes googling variations on "java question mark") and got nothing. So, my question: is there any official documentation on this? I found that C# has a similar operator (the "??" operator), but I'd like to get the documentation for the language I'm working in. Or, is this just a use of the ternary operator that I've never seen before.
Thanks!
EDIT: Link to the article: http://infoworld.com/d/developer-world/12-programming-mistakes-avoid-292
The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.
The related Elvis operator ?: was proposed to make x ?: y
shorthand for x != null ? x : y
, especially useful when x is a complex expression.
这篇关于Java“?"用于检查 null 的运算符 - 它是什么?(不是三元!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!