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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

你可以这样做:

val ans = (exp1 == exp2) then "yes" ?: "no"

通过使用这个扩展:

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

附注:先不要修改上面的中缀函数接受:T?,表达式就会变得逻辑错误。例:如果你先修改它接受空值:T?,那么val ans = (true == true)那么null ?: "abcd", ans将是"abcd",这将是不正确的。

其他回答

Java中等价的三元运算符

a ? b : c

是一个简单的IF在Kotlin一行

if(a) b else c

没有三元操作符(条件?然后:else),因为 普通的如果在这个角色中表现得很好。

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


Null比较的特殊情况

你可以使用Elvis运算符

if ( a != null ) a else b
// equivalent to
a ?: b

您可以在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
}

另一种简单的方法

val value : String = "Kotlin"

value ?: ""

这里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 1.1中出现takeIf后,三元运算符a ?B: c也可以这样表示:

b.takeIf { a } ?: c

在c为空的情况下,这将变得更短:

b.takeIf { a }

使b延迟求值的一般解决方法:

true.takeIf { a }?.let { b } ?: c

还要注意,在Java世界中,典型的空检查像value != null ?在Kotlin中转换为value ?: defaultValue。

类似a != null ?B: c可以翻译成a?让{b} ?: c。


看也是布尔?。如果真的建议在KT-6938应该允许简化一个?b: null表达式到a.f iftrue {b}而不提前计算b。