在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在Kotlin中是无效的代码。
在Kotlin中,与这个表达式等价的是什么?
a ? b : c
这在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()
}
其他回答
例如:var energy: Int = data?.get(position)?.energy?.toInt() ?: 0
在kotlin中,如果你使用?:,它会像这样工作,如果语句将返回null,那么?:0,它将取0或任何你写在这一边的东西。
使用以下中缀函数,我可以覆盖许多常见的用例,几乎与在Python中实现的方式相同:
class TestKotlinTernaryConditionalOperator {
@Test
fun testAndOrInfixFunctions() {
Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(false and "yes" or "no").isEqualTo("no")
Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
Assertions.assertThat("" and "yes" or "no").isEqualTo("no")
Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")
Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
@Suppress("CAST_NEVER_SUCCEEDS")
Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
}
}
infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other
如果你不知道如何使用标准符号,你也可以使用类似这样的中缀来创建/模拟它:
创建一个类来保存目标和结果:
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),因为 普通的如果在这个角色中表现得很好。这里的手动源代码
// 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
(x:Int,y:Int):字符串= if (x>y)"max = $x" else "max = $y"
内联funcation