gpt4 book ai didi

kotlin - 有什么作用? : do in Kotlin?(猫王运算符)

转载 作者:IT老高 更新时间:2023-10-28 13:26:22 29 4
gpt4 key购买 nike

我不知道 ?: 在这种情况下做了什么

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 is true, 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 be null) 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

关于kotlin - 有什么作用? : do in Kotlin?(猫王运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48253107/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com