Kotlin 三元条件运算符 [英] Kotlin Ternary Conditional Operator
问题描述
这个表达式在 Kotlin 中的等价物是什么?
What is the equivalent of this expression in Kotlin?
a ? b : c
这在 Kotlin 中不是有效代码.
This is not valid code in Kotlin.
推荐答案
在 Kotlin 中,if
语句是表达式.所以下面的代码是等价的:
In Kotlin, if
statements are expressions. So the following code is equivalent:
if (a) b else c
表达式和语句之间的区别在这里很重要.在 Java/C#/JavaScript 中,if
形成一个语句,这意味着它不会解析为一个值.更具体地说,您不能将其分配给变量.
The distinction between expression and statement is important here. In Java/C#/JavaScript, if
forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.
// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c
如果您来自一种语言,其中 if
是一个语句,这可能看起来不自然,但这种感觉应该很快就会消退.
If you're coming from a language where if
is a statement, this might seem unnatural but that feeling should soon subside.
这篇关于Kotlin 三元条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!