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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

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

其他回答

在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是语句的语言,这可能看起来不自然,但这种感觉很快就会消失。

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

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

你可以这样做:

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",这将是不正确的。

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

内联funcation

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