是否可以对类型的三元赋值表达式使用简写
boolean x = false;
// ... code ...
a = x ? b : a; // Assigning a to a is pointless
a += x ? 1 : 0; // Adding 0 to a is pointless
我在想一些事情
a = x ? b; // Assign b to a if x is true
a += x ? 1; // Add 1 to a if x is true
并不是说它可以节省很多打字,我只是好奇是否存在这样的东西。我最近在 PHP 7 中发现了null coalesce 运算符,它做了类似的事情。对我来说,它看起来比
if( x ) a = b;
if( x ) a += 1;
因为这些是赋值,所以从左到右阅读时使用三元表达式看起来更自然。假定的重复问题与分配无关,在我看来,这是三元运算符的特殊用例。