Elvis 运算符的不完整代码和 Kotlin 中的添加

Incomplete code with Elvis operator and addition in Kotlin

我正在学习 Kotlin,我碰巧写了这个:

 var nullTest: Int? = null
 println(nullTest?++ ?:0)

尝试编译 运行,我收到“代码不完整”错误。相同于:

 var nullTest: Int? = null
 println(nullTest?+1 ?:0)

而如果我使用:

var nullTest: Int? = null
println(nullTest?.inc() ?:0)

它编译并且运行正确。为什么?为什么我必须使用 .inc() 而不能只使用 + 运算符?

谢谢

您只能对不可为空的变量使用“++”递增和“--”递减。与“+”、“-”、“/”、“*”等运算符的规则相同

如果您有可为空的变量,则必须使用翻译后的方法,例如“.plus()”、“.minus()”、“.div()”、“.inc()”、“ .dec()",带有'?'当然在点之前。

nullTest?.inc() 有效,因为 ?. 是一个运算符:safe-call operator,它仅在值不为 null 时调用以下函数。

nullTest?++ 在 Kotlin 中没有任何意义,因为 ? 本身没有任何意义;没有单独的 ? 运算符。 (此外,++ 需要跟在变量的名称之后,或者 属性 它可以递增。 同样,+ 需要介于两个值之间。)

Kotlin 中的安全调用运算符表示为 ?.,并且未以任何其他方式引用。 Elvis 运算符的工作方式类似于 != null 检查,但如果左侧为空,则将解析到右侧,类似于

val thing: Int? = null
val other: Int = 42

val new: Int = if (thing != null) thing else other

一种更容易理解这一点的方法是,归根结底都归结为函数签名。来自 Kotlin Functions

A function signature is a unique identification of a function for the Kotlin compiler. The signature consists of a function name, its parameters, and the return type.

任何运算符函数,例如 +++- 都有一个相关的函数名称,但它是用于编写该函数引用的特殊语法。 Operator Function Overloads

运算符重载函数没有用于在调用自身之前处理安全空调用的语法。安全调用只能在 . 运算符上调用。

根据你的例子

var nullTest: Int? = null
println(nullTest?+1 ?:0)

如果我们需要一个操作和 null 检查,我们必须像上面用 if 语句显示的那样,否则我们必须将操作分成多行

var nullTest: Int? = null
var backup = 0

// This adds one to the values regardless of if it was null or not
val ourValue = (nullTest ?: backup) + 1

// Uses safe call operator to only increment the nullable value
val otherValue = nullTest?.inc() ?: backup

println(ourValue)
println(otherValue)

或者我们可以用一个 if 来做到这一点,并且只将一个加到潜在的空值

var nullTest: Int? = null
var backup = 0

// Only adds one to the nullable value
val ourValue = if (nullTest != null) nullTest + 1 else backup

println(ourValue)