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.
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.
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.
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.
: _* 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With