Kotlin Ternary Conditional Operator
在Kotlin中,这个表达式的等价物是什么?
| 1 | a ? b : c | 
这不是Kotlin中的有效代码。
在Kotlin,
| 1 | if (a) b else c | 
表达与声明之间的区别在这里很重要。在Java/C 35;/Javascript,edoc1 0 x0 xE4 xE4 xE4 xE4 xE4 xE4 更具体地说,你不能把它分配给一个变量。
ZZU1
如果你是从一种语言来的,那是一种说法,这看起来是不自然的,但感觉应该很快得到支持。
你可以定义你自己的
| 1 | infix fun <T> Boolean.then(param: T): T? = if (this) param else null | 
This would make an 
| 1 | println(condition then"yes" ?:"no") | 
更新:但要做更多的爪哇开关,就像有条件的开关一样,你需要像这样的东西
法国电力公司
法国电力公司请注意Lambda。在我们确定
这是一种Clumsy,这就是为什么对爪哇港三元运算符的高要求存在于Kotlin。
DR
EDCOX1×0是您可以使用的,而不是Java表达式EDCOX1 1。
在Kotlin中,许多控制语句,包括
因此,Kotlin不需要三元运算符。
EDCOX1×0是您可以使用的,而不是Java表达式EDCOX1 1。
我认为后者不太可读,因为每个人都知道
其他替代方案
什么时候
每当在Kotlin中检查条件时,您可能还会看到许多
| 1 2 3 4 | when(a) { true -> b false -> c } | 
扩展
正如其他答案中的许多好例子(Kotlin三元条件运算符)所示,扩展也是一种可行的方法。
For myself I use following extension functions:
| 1 2 | fun T?.or<T>(default: T): T = if (this == null) default else this  fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this | 
首先,一个将返回提供在客体等于零的情况下的缺陷值。第二种表达方式将在同一案例中提供在LAMBDA中。
惯例:
| 1 2 | 1) e?.getMessage().or("unknown") 2) obj?.lastMessage?.timestamp.or { Date() } | 
我个人的代码,比
BLCK1/
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 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没有三元运算符,如EDOCX1&22
所以,你可以:法国电力公司Instead of Java's 
我们还可以使用
| 1 2 3 4 | val max = when(a > b) { true -> a false -> b } | 
这里是Kotlin文献的链接:控制流:if,when,for,while
看着码头
In Kotlin, if is an expression, i.e. it returns a value. Therefore there
is no ternary operator (condition ? then : else),
because ordinary if works fine in this role.
有些角落在其他答案中没有提到。
自从在Kotlin 1.1三元操作员EDOCX1&8中出现Takeif以来,也可以这样表述:
| 1 | b.takeIf { a } ?: c | 
This becomes even shorter in case C is 
| 1 | b.takeIf { a } | 
还注意到,Java世界无核武器区的典型情况,如
可转换为
爪哇
| 1 | int temp = a ? b : c; | 
Equivalent to Kotlin:
| 1 | var temp = if (a) b else c | 
当替换C-like语言的开关操作员时。在简单的形状中,它看起来像这样
| 1 2 3 4 5 6 7 | when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } } | 
Kotlin没有三级操作员。第一个问题。但我们认为,如果这是一种表达,我们可以用内线来做。简单地说,我们必须做-
| 1 | var number = if(n>0)"Positive" else"Negetive" | 
如果我们需要的东西太多,我们就可以在这里。像"的意思
| 1 | var number = if(n>0)"Positive" else if(n<0)"Negative" else"Zero" | 
所以这条线很简单,比三元运算符更容易理解。当我们在爪哇使用的三元手机多于一个三元手机时,它看起来很可怕。但在这里我们有一个清晰的句子。即使我们也能在多条线上写。
As drew noakes quoted,kotlin use if statement as expression,因此,三元条件运算符不需要任何名词,
但随着扩展功能和无限负荷的增加,你可以实现你自己,这是一个例子。
| 1 2 3 4 5 | infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value) class TernaryExpression<out T>(val flag: Boolean, val truly: T?) { infix fun <T> or(falsy: T?) = if (flag) truly else falsy } | 
然后用这个
| 1 2 | val grade = 90 val clazz = (grade > 80) then"A" or"B" | 
你可以在Kotlin做很多事情
使用,使用
| 1 | if(a) b else c | 
使用时
| 1 2 3 4 5 6 7 | when (a) {  true -> print("value b") false -> print("value c") else -> { print("default return in any other case") } } | 
安全性
| 1 | val a = b ?: c | 
另一个有趣的方法是使用
| 1 2 3 4 | when(a) { true -> b false -> b } | 
在一些更复杂的场景中可以分离。而坦率地说,这对我来说比
您可以使用
柯特林的另一个好概念是猫王歌剧。你不需要每次都检查空值。
| 1 | val l = b?.length ?: -1 | 
如果b不为空,则返回长度,否则将执行右侧语句。
Kotlin中没有三元运算符,因为它有if表达式:
| 1 | var d = if (a) b else c | 
Kotlin没有三元操作,但有一些有趣的方法可以解决这个问题。正如其他人所指出的,直接翻译成Kotlin如下:
| 1 | val x = if (condition) result1 else result2 | 
但就个人而言,我认为这可能会变得有点杂乱和难以阅读。库中还内置了一些其他选项。您可以将takeif与ELVIS操作员一起使用:
| 1 | val x = result1.takeIf { condition } ?: result2 | 
发生的情况是takeif命令返回结果1或空值,ELVIS运算符处理空值选项。有一些附加选项,TakeUntil,例如:
| 1 | val x = result1.takeUnless { condition } ?: result2 | 
语言很清楚,你知道这是在做什么。
如果这是一个常用的条件,您也可以做一些有趣的事情,比如使用内联扩展方法。例如,假设我们希望将游戏分数作为int进行跟踪,如果不满足给定条件,我们希望始终返回0:
| 1 | inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this | 
好吧,看起来很难看。但考虑一下使用时的外观:
| 1 2 3 4 5 6 | var score = 0 val twoPointer = 2 val threePointer = 3 score += twoPointer.zeroIfFalse { scoreCondition } score += threePointer.zeroIfFalse { scoreCondition } | 
如您所见,Kotlin在您选择如何表达代码方面提供了很大的灵活性。我的例子有无数的变化,可能我还没有发现。希望这有帮助!
任务:
让我们考虑下面的示例:
| 1 2 3 4 5 6 | if (!answer.isSuccessful()) { result ="wrong" } else { result = answer.body().string() } return result | 
我们需要在Kotlin中使用以下等效物:
return (!answer.isSuccessful())
? "wrong": answer.body().string()

解决:
1.a.您可以在Kotlin中使用
| 1 | return if (!answer.isSuccessful())"wrong" else answer.body().string() | 
1.b.如果你翻转这个
| 1 | return if (answer.isSuccessful()) answer.body().string() else"wrong" | 
2。Kotlin的ELVIS运营商
| 1 | return answer.body()?.string() ?:"wrong" | 
三。或对相应的
| 1 | fun Answer.bodyOrNull(): Body? = if (isSuccessful()) body() else null | 
4。使用
| 1 | return answer.bodyOrNull()?.string() ?:"wrong" | 
5。或者只使用
| 1 2 3 4 | when (!answer.isSuccessful()) { parseInt(str) -> result ="wrong" else -> result = answer.body().string() } | 
希望这有帮助。
您可以在Kotlin中对此使用
| 1 | fun max(a: Int, b: Int) = if (a > b) a else b | 
在Java中,我们可以实现相同但代码更大的代码。
| 1 2 3 | int max(int a, int b) { return a > b ? a : b } | 
记住三元运算符和ELVIS运算符在Kotlin中具有不同的含义,这与许多流行语言不同。执行
因此,可以用
val max = if (a > b)
print("Choose a")
else
print("Choose b")
Kotlin拥有的elvis运算符仅在可为空变量的情况下工作,例如:
If I do something like
value3 = value1 ?: value2 then if value1 is null then value2 would be returned otherwise value1 would be returned.
从这些答案中可以获得更清晰的理解。
在Kotlin中,如果控制流是表达式。所以,它返回一个值。因此,Kotlin不提供三元运算符(条件?然后:其他)。所以,我们可以编写等价的代码。
| 1 | var v=if(a) b else c | 
使用的另一个短路
| 1 2 3 | val value : String ="Kotlin" value ?:"" | 
这里是Kotlin自己检查的零值,如果没有零值,则输入的零值。
为什么要用这样的东西:
| 1 2 3 4 | when(a) { true -> b false -> b } | 
当您可以实际使用类似的东西时(在本例中,
| 1 2 3 4 | when { a -> b else -> b } | 
In Kotlin, there is no ternary operator.
In Kotlin, if is an expression, i.e. it returns a value.
Therefore there is no ternary operator (condition ? then : else),
because ordinary if works fine in this role.
等效于Kotlin
| 1 | var a = if (a) b else c | 
参考文档:控制流:if、when、for、while
使用if else条件语句或when运算符,如下所示
| 1 2 3 4 | when(a) { true -> b false -> b } | 
| 1 2 3 4 5 6 | var a:Int=20 var b:Int=5 val c:Int=15 var d=if(a>b)a else c print("Output is: $d") | 
Kotlin中没有三元运算符,最接近的两种情况是:
- if else as表达式语句
val a = true if(a) print("A is true") else print("A is false") 
- 埃尔维斯算子
If the expression to the left of ?: is not null, the elvis operator
returns it, otherwise it returns the expression to the right. Note
that the right-hand side expression is evaluated only if the left-hand
side is null.
| 1 |  val name = node.getName() ?: throw IllegalArgumentException("name expected") | 
参考文档
通过以下的中缀函数,我可以以与在Python中相同的方式涵盖许多常见的用例:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 | 
当使用apply()时,让我们在处理三元操作时显得非常方便,因为它更优雅,给您空间
| 1 2 3 4 5 6 | val columns: List<String> = ... val band = Band().apply { name = columns[0] album = columns[1] year = columns[2].takeIf { it.isNotEmpty() }?.let { it.toInt() } ?: 0 } | 
example: var energy: Int = data?.get(position)?.energy?.toInt() ?: 0
在科特林,如果你在使用?:如果语句将返回空值,那么它的工作方式将类似于?:0它将需要0或您所写的任何内容。