我不知道 ?:
在这种情况下做了什么
val list = mutableList ?: mutableListOf()
为什么可以修改成这个
val list = if (mutableList != null) mutableList else mutableListOf()
最佳答案
TL;DR:如果结果对象引用 [第一个操作数] 不是 null
,则返回它。否则返回第二个操作数的值(可能是null
)。另外,如果返回null,操作符可以抛出异常。
Elvis 运算符 是许多编程语言的一部分,例如Kotlin 还有 Groovy 或 C#。 我找到 Wikipedia定义相当准确:
In certain computer programming languages, the Elvis operator
?:
is a binary operator that returns its first operand if that operand istrue
, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator,? :
, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.
对于 Kotlin 来说尤其如此:
Some computer programming languages have different semantics for this operator. Instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not
null
, it is returned. Otherwise the value of the second operand (which may benull
) is returned. If the second operand is null, the operator is also able to throw an exception.
一个例子:
x ?: y // yields `x` if `x` is not null, `y` otherwise.
x ?: throw SomeException() // yields `x` if `x` is not null, throws SomeException otherwise
https://stackoverflow.com/questions/48253107/