在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
当前回答
为什么要用这样的东西:
when(a) {
true -> b
false -> b
}
当你实际上可以使用这样的东西(在这种情况下,a是布尔值):
when {
a -> b
else -> b
}
其他回答
在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语句是表达式。所以下面的代码是等价的:
if (a) b else c
表达式和语句之间的区别在这里很重要。在Java/ c# /JavaScript中,if形成语句,意味着它不解析为值。更具体地说,你不能把它赋值给一个变量。
// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c
如果你来自一种If是语句的语言,这可能看起来不自然,但这种感觉很快就会消失。
您可以定义自己的布尔扩展函数,当布尔值为false时返回null,以提供类似于三元运算符的结构:
infix fun <T> Boolean.then(param: T): T? = if (this) param else null
这是a ?B: c表达式翻译成a然后B ?: c,像这样:
println(condition then "yes" ?: "no")
更新: 但是要做一些更类似于java的条件切换,您将需要类似的东西
infix fun <T>布尔值。then(参数:()-> T): T?= if (this) param() else null
Println(条件然后{"yes"} ?: "no") 注意这个。它的内容计算应该推迟,直到我们确定条件为真
这个看起来很笨拙,这就是为什么有很高的要求存在的Java三元运算符移植到Kotlin
如果condition为false则为" error ",否则为"someString"
在编写三元条件运算符之前,让我们考虑以下原型:
if (!answer.isSuccessful()) {
result = "wrong"
} else {
result = answer.body().string()
}
return result
解决方案
你可以用!(逻辑上不是)Kotlin if-expression中的运算符:
return if (!answer.isSuccessful()) "wrong" else answer.body().string()
如果你使用if-expression (expression without !操作符):
return if (answer.isSuccessful()) answer.body().string() else "wrong"
Kotlin 's Elvis operator ?:可以做得更好:
return answer.body()?.string() ?: "wrong"
同样,为相应的Answer类使用扩展函数:
fun Answer.bodyOrNull(): Body? = if (isSuccessful()) body() else null
在扩展函数中,由于Elvis操作符,您可以减少代码:
return answer.bodyOrNull()?.string() ?: "wrong"
或者直接用when条件表达式:
when (!answer.isSuccessful()) {
parseInt(str) -> result = "wrong"
else -> result = answer.body().string()
}
你可以这样做:
val ans = (exp1 == exp2) then "yes" ?: "no"
通过使用这个扩展:
infix fun<T> Boolean.then(first: T): T? = if (this) first else null
附注:先不要修改上面的中缀函数接受:T?,表达式就会变得逻辑错误。例:如果你先修改它接受空值:T?,那么val ans = (true == true)那么null ?: "abcd", ans将是"abcd",这将是不正确的。