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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

在Kotlin中没有三元操作,但是有一些有趣的方法可以解决这个问题。正如其他人指出的那样,直接翻译成Kotlin应该是这样的:

val x = if (condition) result1 else result2

但就我个人而言,我认为这可能会有点混乱,很难阅读。库中还内置了一些其他选项。你可以将takeIf{}与elvis操作符一起使用:

val x = result1.takeIf { condition } ?: result2

这里发生的事情是takeIf{}命令返回result1或null,而elvis操作符处理null选项。还有一些额外的选项,例如takeUnless {}:

val x = result1.takeUnless { condition } ?: result2

语言很清楚,你知道它在做什么。

如果这是一个常用的条件,您还可以做一些有趣的事情,比如使用内联扩展方法。让我们假设我们想要追踪一个Int类型的游戏分数,并且我们想要在给定条件不满足时总是返回0:

inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this     

好吧,这看起来很难看。但是考虑一下它在使用时的样子:

var score = 0
val twoPointer = 2
val threePointer = 3

score += twoPointer.zeroIfFalse { scoreCondition } 
score += threePointer.zeroIfFalse { scoreCondition } 

如您所见,Kotlin在选择如何表达代码方面提供了很大的灵活性。我的例子有无数的变化,可能我还没有发现的方法。我希望这能有所帮助!

其他回答

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

内联funcation

博士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三元条件运算符)所示,扩展还可以帮助解决您的用例。

在Kotlin中,你可以像这样使用三元运算:"add b" else "add c"

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

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