为什么三元运算必须返回值?

Ser*_*erg 3 java compilation ternary-operator

我已阅读相关问题和答案(例如,此处)。但它们是关于是否可以在不赋值的情况下使用三元运算。我的问题是为什么Java不支持它?有一些与编译有关的根本原因吗?有支持它的编程语言吗?

我问的原因是因为一个声明

<condition> ? <do this if true> : <do that if false>
Run Code Online (Sandbox Code Playgroud)

不仅更加优雅并且节省了4行代码,而且与

value = <condition> ? <this if true> : <that if false>
Run Code Online (Sandbox Code Playgroud)

以下是市场数据订单簿实施的实际示例:

public class OrderBook {

    public TreeMap<Integer, Integer> bids = new TreeMap<>(Collections.reverseOrder());
    public TreeMap<Integer, Integer> asks = new TreeMap<>();

    public void quote(boolean isBid, int price, int size) {
        Map<Integer, Integer> book = isBid ? bids : asks;
        if (size == 0) {
            book.remove(price);
        } else {
            book.put(price, size);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个解决方法

public void quote(boolean isBid, int price, int size) {
    Map<Integer, Integer> book = isBid ? bids : asks;
    @SuppressWarnings("unused")
    Integer sizePrevious = (size == 0) ? book.remove(price) : book.put(price, size);
}
Run Code Online (Sandbox Code Playgroud)

但这样看起来会更优雅:

public void quote(boolean isBid, int price, int size) {
    Map<Integer, Integer> book = isBid ? bids : asks;
    (size == 0) ? book.remove(price) : book.put(price, size);
}
Run Code Online (Sandbox Code Playgroud)

这当然不能编译。

ζ--*_*ζ-- 5

这是一个规范问题:

第一个表达式必须是 boolean 或 Boolean 类型,否则会出现编译时错误。

如果第二个或第三个操作数表达式是 void 方法的调用,则会产生编译时错误。

没有什么可以阻止不同的JVM 语言按照您想要的方式foo ? bar() : baz()将 bar 和 baz作为条件进行处理。null在某种程度上,Kotlin 的条件语句使用相同的结构来调用函数和返回值:

val max = if (a > b) a else b
Run Code Online (Sandbox Code Playgroud)

效果一样好

if (a>b) a() else b()
Run Code Online (Sandbox Code Playgroud)

Kotlin 语言设计者可以很容易地选择使用 Javaa?b:c风格的条件运算符,但这很可能被认为更具可读性和表现力。