Kotlin三元条件算子 [英] Kotlin Ternary Conditional Operator
本文介绍了Kotlin三元条件算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Kotlin中这个表达的等价物是什么?
What is the equivalent of this expression in Kotlin?
a ? b : c
这不是Kotlin中的有效代码。
This is not a valid code in Kotlin.
推荐答案
在Kotlin中,如果
语句是表达式。所以下面的代码是等价的:
In Kotlin, if
statements are expressions. So the following code is equivalent:
if (a) b else c
表达式和语句之间的区别在这里很重要。在Java / C#/ JavaScript中,如果
形成一个语句,意味着它没有解析为某个值。更具体地说,你不能将它分配给变量。
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 you're coming from a language where if
is a statement, this might seem unnatural but that feeling should soon subside.
这篇关于Kotlin三元条件算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文