简体   繁体   English

Java在三元操作中声明变量。 可能吗?

[英]Java declare variable in ternary operation. Is it possible?

Say we have some city with String getZIP() method. 假设我们有一些使用String getZIP()方法的city I want to print value of ZIP or don't print anything if ZIP is null. 我想打印ZIP的值,或者如果ZIP为null,则不打印任何内容。

I can do it in one line of code with ternary operation: 我可以使用三元运算在一行代码中做到这一点:

System.out.print(city.getZIP() == null ? "" : city.getZIP())

The question is: can I do the same without calling .getZIP() twice? 问题是:是否可以执行相同的操作而无需两次调用.getZIP() Something like: 就像是:

System.out.print(String zip = city.getZIP() == null ? "" : zip) //syntax error here

Define the variable in a separate line : 在单独的行中定义变量:

String zip = city.getZIP();
System.out.print(zip == null ? "" : zip);

You can assign the value to an existing variable, but not create one inside the ternery condition. 您可以将值分配给现有变量,但不能在ternery条件内创建一个值。

Something like, 就像是,

String zip; // Created elsewhere but not assigned to city.getZip().
System.out.print(((zip = city.getZIP()) == null) ? "" : zip)

But you can't declare a new variable inside. 但是您不能在其中声明一个新变量。

I have a completely different solution for you: don't do that . 我为您提供了一个完全不同的解决方案: 不要那样做

Do not put methods on your classes that return null as "legit" result. 不要在您的类上放置将“ neggit”结果返回null的方法。

For example: zip code could / should be its own class. 例如:邮政编码可以/应该是它自己的类。 And then you simply declare some singleton instance of ZIP to represent "ZIP code is undefined". 然后,您只需声明一些ZIP单例实例即可表示“ ZIP代码未定义”。 And then calling toString on "UnknownZip" ... just gives an empty string for example. 然后在“ UnknownZip”上调用toString ...例如,仅给出一个空字符串。

Using null as return value always opens up the chance for NullPointerExceptions. 使用null作为返回值总是会打开NullPointerExceptions的机会。

So - don't do that. 所以-不要那样做。

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

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