问题
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.
回答1:
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.
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"
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"
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.
回答2:
To add to what @Jesper said, if you find if
-else
too verbose, Scalaz provides two more terser alternatives: A ternary boolean operator (?
, |
) a la C-like languages, and fold
function.
scala> import scalaz._
import scalaz._
scala> import Scalaz._
import Scalaz._
scala> (3 > 2) ? "True" | "False"
res59: java.lang.String = True
scala> (3 > 2).fold("True", "False")
res60: java.lang.String = True
回答3:
In approximate order of importance:
1) The :
symbol is reserved for type annotation
2) In Scala, symbols can be used as identifiers for method and value names. There are only a limited number of these available on a standard keyboard, so if you decide to make two of these into keywords, you're reducing the pool of operators that can be used (see footnote for why they'd have to be keywords)
3) As Jesper says, the more powerful if
/ else
already fulfil this role, so the gain is marginal
4) Scala also has pattern matching which fulfils a similar role with the match
keyword, in a much more general way. E.g. what if your expression evaluates to a something that is not a boolean?
5) It would add additional compiler complexity. Scala prefers simplicity and uniformity to special cases
6) It's a hangover from C, and is really quite an odd syntax. Scala has enough odd-looking syntax
Footnote:
While it's possible to come up with a reasonable scheme to emulate ? :
as methods (see Ternary operator typing), it's not as viable as keywords. It is complex to handle typing properly when the "true" and "false" alternatives are of different numberic types, operator precedence is a problem since you need operators that are lower priority than anything else (or else you have to use parentheses), and performance will likely suffer due to the runtime nature of the implementation.
来源:https://stackoverflow.com/questions/8238184/why-not-provide-an-operator-in-scala