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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:

创建一个类来保存目标和结果:

data class Ternary<T>(val target: T, val result: Boolean)

创建一些中缀函数来模拟三元操作

infix fun <T> Boolean.then(target: T): Ternary<T> {
    return Ternary(target, this)
}

infix fun <T> Ternary<T>.or(target: T): T {
    return if (this.result) this.target else target
}

然后你就可以这样使用它了:

val collection: List<Int> = mutableListOf(1, 2, 3, 4)

var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"

其他回答

在Kotlin中没有三元运算符,最封闭的是下面两种情况,

If else作为表达式语句

val a = true if(a) print(" a是真")else print(" a是假")

猫王运营商

如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。

 val name = node.getName() ?: throw IllegalArgumentException("name expected")

参考文档

博士TL;

if (a) b else c

^是你可以用来代替三元运算符表达式a ?b: c,这是Kotlin语法不允许的。


在Kotlin中,许多控制语句,例如if、when,甚至try,都可以用作表达式。因此,这些语句的结果可以赋值给变量,也可以从函数返回,等等。

从语法上讲,不需要三元运算符

由于使用了Kotlin的表达式,该语言实际上并不需要三元运算符。

if (a) b else c

你可以用什么来代替三元运算符表达式a ?B: c。

我认为前一种表达更有可读性,因为每个人都知道如果其他人做了什么,然而?:如果您不熟悉语法,则不太清楚。

然而,我不得不承认,我经常错过更方便的三元运算符。


其他备选方案

when

您还可以看到在检查条件时Kotlin中使用的构造。这也是一种以另一种方式表达if-else级联的方法。下面以OTs为例。

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

扩展

正如其他答案中的许多好例子(Kotlin三元条件运算符)所示,扩展还可以帮助解决您的用例。

when替换c类语言的切换操作符。最简单的形式是这样的

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

在Kotlin中没有三元运算符。乍一看,这似乎有问题。但是我们可以用内联if else语句因为这是表达式。我们要做的就是

var number = if(n>0) "Positive" else "Negetive"

这里我们可以用else if来阻塞我们需要的太多。像- - - - - -

var number = if(n>0) "Positive" else if(n<0) "Negative" else "Zero"

这一行比三元运算符简单易读。当我们在Java中使用多个三元运算符时,这看起来很可怕。但是这里我们有一个清晰的语法。甚至我们也可以把它写成多行。

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