Why not provide an operator ? : in scala

爱国者 picture 爱国者 · Nov 23, 2011 · Viewed 9.1k times · Source

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.

Answer

Jesper picture Jesper · Nov 23, 2011

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.