为什么不提供运营商? :在斯卡拉 [英] Why not provide an operator ? : in scala
问题描述
有一个运营商? :Java中的
,可用于根据布尔表达式选择值。例如,表达式 3> 2? true:false
将返回一个字符串true
。我知道我们可以使用 if
表达式来做到这一点,但我更喜欢这种风格,因为它简洁而优雅。
There is an operator ? :
in Java which can be used to select a value according to the boolean expression. For example, the expression 3 > 2 ? "true" : false
will return a string "true"
. I know we can use if
expression to do this, but I will prefer this style because it is concise and elegant.
推荐答案
在Java中,如果
和<$之间存在差异C $ C>? :,如果是语句而,那是
? :
是一个表达式。在Scala中,如果
也是表达式:它返回一个值,您可以将其分配给变量。
In Java, there is a difference between if
and ? :
and that is that if
is a statement while ? :
is an expression. In Scala, if
is also an expression: it returns a value that you can for example assign to a variable.
Scala中的如果
更像是? :Java中的
而不是Java中的 if
:
The if
in Scala is much more like ? :
in Java than the if
in Java:
// In Scala 'if' returns a value that can be assigned to a variable
val result = if (3 > 2) "yes" else "no"
你不能用Java做到这一点:
You cannot do this in Java:
// Illegal in Java, because 'if' is a statement, not an expression
String result = if (3 > 2) "yes" else "no"
那么,实际上没有必要拥有? :
在Scala中,因为它与完全相同,如果
,但是使用其他(更加模糊的)语法。
So, it is really not necessary to have ? :
in Scala because it would be exactly the same as if
, but with alternative (more obscure) syntax.
这篇关于为什么不提供运营商? :在斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!