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

a ? b : c

这在Kotlin中是无效的代码。


当前回答

为什么要用这样的东西:

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

当你实际上可以使用这样的东西(在这种情况下,a是布尔值):

when {
  a -> b
  else -> b
}

其他回答

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

内联funcation

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

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

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), 因为普通的if在这个角色中很管用。

在Kotlin中没有三元运算符,最封闭的是下面两种情况,

If else作为表达式语句

val a = true if(a) print(" a是真")else print(" a是假")

猫王运营商

如果?:左边的表达式不为空,则猫王操作符 返回它,否则返回右边的表达式。请注意 右边的表达式只在左边的表达式被求值 Side为空。

 val name = node.getName() ?: throw IllegalArgumentException("name expected")

参考文档

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

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() }

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