gpt4 book ai didi

ternary-operator - Kotlin 等价于三元运算符

转载 作者:IT老高 更新时间:2023-10-28 13:43:44 25 4
gpt4 key购买 nike

所以在 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 .

关于ternary-operator - Kotlin 等价于三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34935918/

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