赋值不会 return 无效

Assignment does not return void

我在 Google Guava Github 上找到了这段代码,但我不明白为什么在第 5 行 rowMap 方法在满足条件的情况下不会 return 无效 :

private transient @MonotonicNonNull Map<R, Map<C, V>> rowMap;

public Map<R, Map<C, V>> rowMap() {
  Map<R, Map<C, V>> result = rowMap;
  return (result == null) ? rowMap = createRowMap() : result;
}

Map<R, Map<C, V>> createRowMap() {
  return new RowMap();
}

这一行是否等同于:

if (result == null) {
  return rowMap = createRowMap();
} else {
  return result;
}

然后对 rowMap 的赋值将 return 无效。我错过了什么?

What did I miss?

赋值表达式的结果是赋值的事实。 :-) 因此在该代码中,调用 createRowMap 的结果被分配给 rowMap 并且 作为 rowMap 函数的结果返回.就像:

a = b = 42;

...将 b 设置为 42,然后将 a 设置为 42b = 42 赋值的结果)。

效果就好像代码是这样写的:

public Map<R, Map<C, V>> rowMap() {
  Map<R, Map<C, V>> result = rowMap;
  if (result != null) {
    return result;
  }
  rowMap = createRowMap();
  return rowMap;
}

赋值表达式varibale = value的求值结果为value,try:

int a;
System.out.println(a = 1); // 1

所以它等于:

if (result == null) {
    rowMap = createRowMap();
    return rowMap;
}

See jls for more:

When an expression in a program is evaluated (executed), the result denotes one of three things:

  • A variable (§4.12) (in C, this would be called an lvalue)

  • A value (§4.2, §4.3)

  • Nothing (the expression is said to be void)

...

An expression denotes nothing if and only if it is a method invocation (§15.12) that invokes a method that does not return a value, that is, a method declared void (§8.4).