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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

如果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语句作为表达式, 所以三元条件运算符不再是必要的,

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

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"

看看这些文件:

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

在使用apply()时,let在处理三元操作时似乎非常方便,因为它更优雅,并为您提供了空间

val columns: List<String> = ...
val band = Band().apply {
    name = columns[0]
    album = columns[1]
    year = columns[2].takeIf { it.isNotEmpty() }?.let { it.toInt() } ?: 0
}

使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在Python中实现的方式相同:

class TestKotlinTernaryConditionalOperator {

    @Test
    fun testAndOrInfixFunctions() {
        Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(false and "yes" or "no").isEqualTo("no")

        Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat("" and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
        @Suppress("CAST_NEVER_SUCCEEDS")
        Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
    }
}

infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other

您可以在Kotlin中以多种方式实现它

如果使用 如果(a) b else c 使用时 当(a) { True ->打印("value b") 错误->打印("value c") Else -> { 打印("在任何其他情况下默认返回") } } 空安全 Val a = b ?: c