假设我们有一些city
与String getZIP()
方法。我想打印ZIP的值,或者如果ZIP为空则不打印任何内容。
我可以使用三元运算在一行代码中完成它:
System.out.print(city.getZIP() == null ? "" : city.getZIP())
问题是:如果不两次调用.getZIP()
,我可以这样做吗?就像是:
System.out.print(String zip = city.getZIP() == null ? "" : zip) //syntax error here
您可以将值分配给现有变量,但不能在ternery条件内创建一个。
就像是,
String zip; // Created elsewhere but not assigned to city.getZip().
System.out.print(((zip = city.getZIP()) == null) ? "" : zip)
但你不能在里面声明一个新的变量。
在单独的行中定义变量:
String zip = city.getZIP();
System.out.print(zip == null ? "" : zip);
我有一个完全不同的解决方案:不要那样做。
不要将返回null的类放在“合法”结果上。
例如:邮政编码可以/应该是它自己的类。然后你只需声明一些ZIP的单例实例来表示“邮政编码是未定义的”。然后在“UnknownZip”上调用toString ...例如,只给出一个空字符串。
使用null作为返回值总是为NullPointerExceptions打开机会。
所以 - 不要这样做。