在Kotlin中,与这个表达式等价的是什么?

a ? b : c

这在Kotlin中是无效的代码。


当前回答

你可以使用var a= if (a) b else c来代替三元运算符。

kotlin的另一个好概念是Elvis运算符。你不需要每次都检查null。

val l = b?.length ?: -1

如果b不为空,则返回length,否则执行右边语句。

其他回答

在Java中,if是语句,但在Kotlin中if是表达式。它被称为表达式,因为它比较a和b的值并返回最大值。因此,在Kotlin中没有三元运算符(a>b)?A:b,因为它被if表达式所取代。

您可以定义自己的布尔扩展函数,当布尔值为false时返回null,以提供类似于三元运算符的结构:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

这是a ?B: c表达式翻译成a然后B ?: c,像这样:

println(condition then "yes" ?: "no")

更新: 但是要做一些更类似于java的条件切换,您将需要类似的东西

infix fun <T>布尔值。then(参数:()-> T): T?= if (this) param() else null

Println(条件然后{"yes"} ?: "no") 注意这个。它的内容计算应该推迟,直到我们确定条件为真

这个看起来很笨拙,这就是为什么有很高的要求存在的Java三元运算符移植到Kotlin

如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:

创建一个类来保存目标和结果:

data class Ternary<T>(val target: T, val result: Boolean)

创建一些中缀函数来模拟三元操作

infix fun <T> Boolean.then(target: T): Ternary<T> {
    return Ternary(target, this)
}

infix fun <T> Ternary<T>.or(target: T): T {
    return if (this.result) this.target else target
}

然后你就可以这样使用它了:

val collection: List<Int> = mutableListOf(1, 2, 3, 4)

var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"

在Kotlin中没有三元运算符,最封闭的是下面两种情况,

If else作为表达式语句

val a = true if(a) print(" a是真")else print(" a是假")

猫王运营商

如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。

 val name = node.getName() ?: throw IllegalArgumentException("name expected")

参考文档

看看这些文件:

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