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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

另一个有趣的方法是在以下情况使用:

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

在一些更复杂的场景中非常方便。老实说,这对我来说比……其他的……

其他回答

这里的其他答案,例如takeIf假设x = (a != null) ?A: c或x = (A != null) ?a.method(): c,但这实际上并不等同于x = a ?B: c

实现一个真正等价的三元运算符与空安全检查(即x = (a != null) ?c)你可以用let代替takeIf。

Val x = a?让{b} ?: c

其中b可能是也可能不是调用a上某项内容的方法。

其他答案中没有提到的一些极端情况。

自从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。

使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在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

(x:Int,y:Int):字符串= if (x>y)"max = $x" else "max = $y"

内联funcation

在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