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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

(x:Int,y:Int):字符串= if (x>y)"max = $x" else "max = $y"

内联funcation

其他回答

在kotlin中没有三元运算符,因为if else块返回值。

所以,你可以: Val Max = if (a > b) a else b 而不是java的Max = (a > b) ?B: c

我们也可以使用when construction,它也返回值:

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

下面是kotlin文档的链接:Control Flow: if, when, for, while

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

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

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表达式。在Kotlin中if是一个带有结果值的表达式。所以在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
}

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

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
}