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

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

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

https://stackoverflow.com/questions/48253107/

相关文章:

java - Kotlin 'when' 语句与 Java 'switch'

unit-testing - 在 Kotlin 中测试预期的异常

kotlin - Kotlin 中的 "receiver"是什么?

lambda - 传递 lambda 而不是接口(interface)

list - 如何在 Kotlin 中初始化 List

android - 找不到字段的 setter - 将 Kotlin 与 Room 数据库结合使用

java - Android 动画 Alpha

android - Kotlin: "return@"是什么意思?

kotlin - 函数中Unit-return的目的是什么

kotlin - 如何在 Kotlin 中同时捕获多个异常?