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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:

创建一个类来保存目标和结果:

data class Ternary<T>(val target: T, val result: Boolean)

创建一些中缀函数来模拟三元操作

infix fun <T> Boolean.then(target: T): Ternary<T> {
    return Ternary(target, this)
}

infix fun <T> Ternary<T>.or(target: T): T {
    return if (this.result) this.target else target
}

然后你就可以这样使用它了:

val collection: List<Int> = mutableListOf(1, 2, 3, 4)

var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"

其他回答

Java中等价的三元运算符

a ? b : c

是一个简单的IF在Kotlin一行

if(a) b else c

没有三元操作符(条件?然后:else),因为 普通的如果在这个角色中表现得很好。

https://kotlinlang.org/docs/reference/control-flow.html#if-expression


Null比较的特殊情况

你可以使用Elvis运算符

if ( a != null ) a else b
// equivalent to
a ?: b

如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:

创建一个类来保存目标和结果:

data class Ternary<T>(val target: T, val result: Boolean)

创建一些中缀函数来模拟三元操作

infix fun <T> Boolean.then(target: T): Ternary<T> {
    return Ternary(target, this)
}

infix fun <T> Ternary<T>.or(target: T): T {
    return if (this.result) this.target else target
}

然后你就可以这样使用它了:

val collection: List<Int> = mutableListOf(1, 2, 3, 4)

var exampleOne = collection.isEmpty() then "yes" or "no"
var exampleTwo = (collection.isNotEmpty() && collection.contains(2)) then "yes" or "no"
var exampleThree = collection.contains(1) then "yes" or "no"

另一个有趣的方法是在以下情况使用:

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

在一些更复杂的场景中非常方便。老实说,这对我来说比……其他的……

另一种简单的方法

val value : String = "Kotlin"

value ?: ""

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

你可以使用var a= if (a) b else c来代替三元运算符。

kotlin的另一个好概念是Elvis运算符。你不需要每次都检查null。

val l = b?.length ?: -1

如果b不为空,则返回length,否则执行右边语句。