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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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中,if语句是表达式。所以下面的代码是等价的:

if (a) b else c

表达式和语句之间的区别在这里很重要。在Java/ c# /JavaScript中,if形成语句,意味着它不解析为值。更具体地说,你不能把它赋值给一个变量。

// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c

如果你来自一种If是语句的语言,这可能看起来不自然,但这种感觉很快就会消失。

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表达式。在Kotlin中if是一个带有结果值的表达式。所以在Kotlin中,我们可以写

fun max(a: Int, b: Int) = if (a > b) a else b

在Java中,我们可以用更大的代码实现同样的效果

int max(int a, int b) {
return a > b ? a : b
}

为什么要用这样的东西:

when(a) {
  true -> b
  false -> b
}

当你实际上可以使用这样的东西(在这种情况下,a是布尔值):

when {
  a -> b
  else -> b
}