是什么?:在科特林做什么? (猫王操作员) [英] What does ?: do in Kotlin? (Elvis Operator)
问题描述
在这种情况下,我不知道?:
的作用
I can't figure out what ?:
does in for example this case
val list = mutableList ?: mutableListOf()
以及为什么可以对此进行修改
and why can it be modified to this
val list = if (mutableList != null) mutableList else mutableListOf()
推荐答案
TL; DR:如果生成的对象引用[第一个操作数]不是null
,则将其返回.否则,将返回第二个操作数的值(可能为null
)
TL;DR: If the resulting object reference [first operand] is not null
, it is returned. Otherwise the value of the second operand (which may be null
) is returned
Elvis运算符是许多编程语言的一部分,例如Kotlin以及Groovy或C#. 我发现 Wikipedia 定义非常准确:
The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#. I find the Wikipedia definition pretty accurate:
在某些计算机编程语言中, Elvis运算符
?:
是 binary运算符,如果该操作数为true
,则返回其第一个操作数,否则求值并返回其第二个操作数.它是这些语言(以及许多其他语言)中的三元条件运算符的变体 :Elvis运算符是三元运算符,省略了第二个操作数
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,以下情况尤其如此:
The following is especially true for Kotlin:
某些计算机编程语言对此运算符具有不同的语义. 代替第一个操作数必须产生布尔值,它必须导致对象引用.如果生成的对象引用不是
null
,则将其返回.否则,将返回第二个操作数的值(可能为null
).
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.
一个例子:
x ?: y // yields `x` if `x` is not null, `y` otherwise.
这篇关于是什么?:在科特林做什么? (猫王操作员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!