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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

看看这些文件:

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

其他回答

Kotlin没有三元运算符。你可以使用正则if表达式,如下所示:

If (condition) exp1 else exp2

此外,在Kotlin中if不是语句而是表达式(即它计算为一个值),如果在if分支的主体中有多条语句(或else或else if的主体),块的最后一行就是该分支的值。例如:

if (a>b) {
    println("a is greater than b")
    a // value of this if
} else {
    println("b is greater than a")
    b // value of else
}

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

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

第一个函数将在object = null的情况下返回提供的默认值。第二个将在相同情况下计算lambda中提供的表达式。

用法:

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

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

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

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

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"

在Kotlin中没有三元运算符。乍一看,这似乎有问题。但是我们可以用内联if else语句因为这是表达式。我们要做的就是

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

这里我们可以用else if来阻塞我们需要的太多。像- - - - - -

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

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

在Kotlin中,if是一个表达式,即它返回一个值。因此 没有三元操作符(条件?然后: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