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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

看看这些文件:

在Kotlin中,if是一个表达式,即它返回一个值。因此, 没有三元运算符(条件?然后:else), 因为普通的if在这个角色中很管用。

其他回答

看看这些文件:

在Kotlin中,if是一个表达式,即它返回一个值。因此, 没有三元运算符(条件?然后:else), 因为普通的if在这个角色中很管用。

记住,与许多流行语言不同,三元运算符和猫王运算符在Kotlin中具有不同的含义。表情干什么?在Kotlin编译器中value1: value2会给你不好的单词,不像任何其他语言,因为在Kotlin中没有三元运算符,就像官方文档中提到的那样。原因是if、when和try-catch语句本身返回值。

那么,做表情?Value1: value2可以替换为

Val Max = if (a > b) print(选择一个) 其他的 打印(“选择b”)

Kotlin拥有的Elvis运算符只适用于可空变量的情况,例如:

如果我执行类似value3 = value1 ?: value2这样的操作,那么如果value1为null,那么将返回value2,否则将返回value1。

从这些回答中可以得到更清晰的理解。

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

另一种简单的方法

val value : String = "Kotlin"

value ?: ""

这里kotlin本身检查空值,如果它为空,则传递空字符串值。

Java

int temp = a ? b : c;

相当于Kotlin:

var temp = if (a) b else c