Kotlin三元条件运算符

Kotlin中这个expression的等价物是什么?

a ? b : c 

这不是Kotlin中的有效代码。

在Kotlin中, if语句是expression式。 所以下面的代码是等价的:

 if (a) b else c 

expression和声明之间的区别在这里很重要。 在Java / C#/ JavaScript中, if形成一个声明,意味着它不解析为一个值。 更具体地说,你不能把它分配给一个variables。

 // Valid Kotlin, but invalid Java/C#/JavaScript var v = if (a) b else c 

如果你是来自一种语言, if是一个声明,这可能看起来不自然,但这种感觉应该很快就会消退。

您可以定义自己的Boolean扩展函数,当Boolean值为false时返回null ,以提供类似于三元运算符的结构:

 infix fun  Boolean.then(param: T): T? = if (this) param else null 

这会使a ? b : c a ? b : cexpression式转换成a then b ?: c ,如下所示:

 println(condition then "yes" ?: "no") 

更新:但是要做更多的类似于Java的条件切换,你将需要类似的东西

infix fun Boolean.then(param: () -> T): T? = if (this) param() else null

println(condition then { "yes" } ?: "no")注意lambda。 其内容计算应该推迟到确定condition true为止

这个看起来很笨拙, 这就是为什么要把Java三元运算符转换成Kotlin的要求很高的原因

对于我自己,我使用以下扩展function:

 fun T?.or(default: T): T = if (this == null) default else this fun T?.or(compute: () -> T): T = if (this == null) compute() else this 

如果对象等于null,第一个将返回提供的默认值。 其次将在同一个案中评估lambda中提供的expression式。

用法:

 1) e?.getMessage().or("unknown") 2) obj?.lastMessage?.timestamp.or { Date() } 

就我个人而言,代码的上面比构建内联更具有可读性

在Kotlin中, if是一个expression式,即它返回一个值。 因此没有三元运算符(condition ? then : 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 

看看文档 :

在Kotlin中,如果是一个expression式,即它返回一个值。 所以没有三元运算符(condition?then:else),因为普通的如果在这个角色中工作的很好。

kotlin中没有三进制运算符 ,因为if else块返回值

所以,你可以这样做: val max = if (a > b) a else b而不是java的max = (a > b) ? b : c max = (a > b) ? b : c

我们也可以when施工的when使用,也可以返回值:

 val max = when(a > b) { true -> a false -> b } 

这里是文档链接https://kotlinlang.org/docs/reference/control-flow.html

其他答案中没有提到的一些角落案例。

自Kotlin 1.1出现以后 ,三元运算符a ? b : c a ? b : c也可以这样表示:

 b.takeIf { a } ?: c 

在c为null情况下,这变得更短:

 b.takeIf { a } 

还要注意在Java世界中的典型空值检查如value != null ? value : defaultValue value != null ? value : defaultValue在ideotmatic Kotlin中翻译为value ?: defaultValue

类似a != null ? b : c a != null ? b : c可以翻译成a?.let { b } ?: c

Java的

 int temp = a ? b : c; 

相当于Kotlin:

 var temp = if (a) b else c 

当替换C语言的开关操作符时。 最简单的forms是这样的

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

Kotlin没有三元操作符。 乍一看似乎有问题。 但是我们可以用inline if else语句来实现,因为这是expression式。 我们只需要做 –

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

如果我们需要的话,我们也可以阻止。 喜欢-

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

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

正如Drew Noakes所引用的,kotlin使用if语句作为expression式,所以三元条件运算符不再是必要的,

但是用扩展函数和中缀重载,你可以自己实现,这里是一个例子

 infix fun  Boolean.then(value: T?) = TernaryExpression(this, value) class TernaryExpression(val flag: Boolean, val truly: T?) { infix fun  or(falsy: T?) = if (flag) truly else falsy } 

然后像这样使用它

 val grade = 90 val clazz = (grade > 80) then "A" or "B" 

另一个有趣的方法是使用when

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

在一些更复杂的情况下可以非常方便。 说实话,这对我来说比if ... else ...更可读if ... else ...

你可以在Kotlin做很多事情

  1. 使用if

     if(a) b else c 
  2. 使用时

     when (a) { true -> print("value b") false -> print("value c") else -> { print("default return in any other case") } } 
  3. 零安全

     val a = b ?: c 

语句 – >expression式

在Kotlin中,许多控制语句,包括ifwhen ,甚至try都可以用作expression式 。 这意味着,它有一个结果,可以分配给一个variables,从一个函数返回等等。

不需要三元运算符

话虽如此, Kotlin并不需要三元运算符

if (a) b else c是你可以使用的而不是Javaexpression式a ? b : c a ? b : c

国际海事组织 ,后者是可读性较差,因为每个人都知道什么ifelse ,而? : ? :很不方便。 所以我同意三元运营商无权在Kotlin中存在。

其他选择

什么时候

在Kotlin中检查条件when您可能会看到很多结构。 这也是以其他方式expressionif-else级联的方式。 以下对应于你的例子。

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

扩展

在其他答案中显示了很多很好的示例( https://stackoverflow.com/a/39687177/8073652 ),扩展也可以成为一种方法。

你可以在Kotlin中使用ifexpression式。 在Kotlin中if是一个结果值的expression式。 所以在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 } 

Kotlin没有三元操作,但有一些有趣的方法来解决这个问题。 正如其他人所指出的那样,直接翻译成科特林就是这样的:

 val x = if (condition) result1 else result2 

但是,我个人认为可能会有点混乱,难以阅读。 图书馆还有其他一些选项。 你可以用一个elvis操作符来使用takeIf {}:

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

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

 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为您选择如何expression代码提供了很大的灵活性。 我的例子有无数的变化,可能我还没有发现。 我希望这有帮助!

根据我自己的Kotlin文档,我使用以下代码:

  val max = if (a > b) a else b 

和:

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

如果您想了解更多信息,请查看此链接https://kotlinlang.org/docs/reference/control-flow.html

另一个短的方法来使用

 val value : String = "Kotlin" value ?: "" 

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

有了下面的中缀函数,我可以覆盖很多常见的用例,几乎和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  Boolean?.and(other: E?): E? = if (this == true) other else null infix fun  CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null infix fun  Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null infix fun  Any?.and(other: E?): E? = if (this != null) other else null infix fun  E?.or(other: E?): E? = this ?: other 

在Kotlin, 没有三元运算符

在Kotlin中,如果是一个expression式,即它返回一个值。

所以没有三元运算符(condition?then:else),因为普通的如果在这个角色中工作的很好。

相当于Kotlin

 var a = if (a) b else c 

参考文档 : https : //kotlinlang.org/docs/reference/control-flow.html

当使用apply()时,在处理三元操作时,让它看起来非常方便,因为它更优雅,给你空间

在这里输入图像说明