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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

Java

int temp = a ? b : c;

相当于Kotlin:

var temp = if (a) b else c

其他回答

如果condition为false则为" error ",否则为"someString"

在编写三元条件运算符之前,让我们考虑以下原型:

if (!answer.isSuccessful()) {
    result = "wrong"
} else {
    result = answer.body().string()
}

return result

解决方案

你可以用!(逻辑上不是)Kotlin if-expression中的运算符:

return if (!answer.isSuccessful()) "wrong" else answer.body().string()

如果你使用if-expression (expression without !操作符):

return if (answer.isSuccessful()) answer.body().string() else "wrong"

Kotlin 's Elvis operator ?:可以做得更好:

return answer.body()?.string() ?: "wrong"

同样,为相应的Answer类使用扩展函数:

fun Answer.bodyOrNull(): Body? = if (isSuccessful()) body() else null

在扩展函数中,由于Elvis操作符,您可以减少代码:

return answer.bodyOrNull()?.string() ?: "wrong"

或者直接用when条件表达式:

when (!answer.isSuccessful()) {
    parseInt(str) -> result = "wrong"
    else -> result = answer.body().string()
}

在Kotlin中,if是一个表达式,即它返回一个值。因此 没有三元操作符(条件?然后:else),因为 普通的如果在这个角色中表现得很好。这里的手动源代码

// Traditional usage 
var max = a 
if (a < b) max = b

// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

// As expression 
val max = if (a > b) a else b

正如德鲁·诺克斯引用的,kotlin使用if语句作为表达式, 所以三元条件运算符不再是必要的,

但是使用扩展函数和中缀重载,你可以自己实现,这里有一个例子

infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)

class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
    infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}

然后像这样使用它

val grade = 90
val clazz = (grade > 80) then "A" or "B"

您可以定义自己的布尔扩展函数,当布尔值为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

在kotlin中没有三元运算符,因为if else块返回值。

所以,你可以: Val Max = if (a > b) a else b 而不是java的Max = (a > b) ?B: c

我们也可以使用when construction,它也返回值:

val max = when(a > b) {
    true -> a
    false -> b
}

下面是kotlin文档的链接:Control Flow: if, when, for, while