Kotlin相当于三元运算符[重复]

问题描述 投票:5回答:1

这个问题在这里已有答案:

所以在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等价物?

ternary-operator kotlin
1个回答
14
投票

Kotlin没有三元运营商。

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

在Kotlin中,if是一个表达式,即它返回一个值。因此没有三元运算符(条件?则:else),因为普通的if在这个角色中工作正常。

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

© www.soinside.com 2019 - 2024. All rights reserved.