Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not provide an operator ? : in scala [closed]

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.

like image 865
爱国者 Avatar asked Nov 23 '11 06:11

爱国者


People also ask

What does the operator :: mean in Scala?

An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: Arithmetic Operators.

What does =!= Mean in Scala?

It has no special meaning whatsoever. It is also not a well-known method name in Scala. It seems to come from some library; you need to look at the documentation of whatever library you are using to figure out what it does.

What is operator overloading in Scala?

Operator Overloading in Scala Scala supports operator overloading, which means that the meaning of operators (such as * and + ) may be defined for arbitrary types. Example: a complex number class: class Complex(val real : Double, val imag : Double) { def +(other : Complex) = new Complex( real + other.

What does _* mean in Scala?

: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs.


1 Answers

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.

like image 144
Jesper Avatar answered Sep 22 '22 01:09

Jesper