Kotlin 等价于三元运算符

Kotlin equivalent of ternary operator

所以在 java 中我们有三元运算符 (?),它有时有助于简化 if-else 内联计算的某些值。例如:

myAdapter.setAdapterItems(
            textToSearch.length == 0
            ? noteList
            : noteList.sublist(0, length-5)
)

我知道 kotlin 中的等价物是:

myAdapter.setAdapterItems(
                if(textToSearch.length == 0)
                    noteList
                else
                    noteList.sublist(0, length-5) 
)

但我只是喜欢 Java 中的三元运算符,用于短表达式条件,以及将值传递给方法时。是否有任何 Kotlin 等效项?

Kotlin 中没有三元运算符。

https://kotlinlang.org/docs/reference/control-flow.html

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

你可以找到更详细的解释here