Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala operator oddity

Tags:

scala

When I invoke + on 2 I get an Int back, but when its done using explicit method call I get Double instead.

scala> 2+2
res1: Int = 4

scala> 2.+(2)
res2: Double = 4.0

It seems that .+() is invoked on implicit converted Int to Double.

scala> 2.+
<console>:16: error: ambiguous reference to overloaded definition,
both method + in class Double of type (x: Char)Double
and  method + in class Double of type (x: Short)Double
match expected type ?
              2.+
                ^

Why is that so ?

like image 473
Lukasz Avatar asked Mar 11 '12 12:03

Lukasz


People also ask

What is :: operator in Scala?

The ::() operator in Scala is utilized to add an element to the beginning of the List. Method Definition: def ::(x: A): List[A] Return Type: It returns the stated list after adding an element to the beginning of it.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

Can you do += in Scala?

There are no ++ or -- operators in Scala (use += or -=) Second, Scala encourages the use of immutable values, and with immutable values you'll have no need for these operators.


1 Answers

In Scala 2.9 and before, 2. is interpreted as 2.0 so the ambiguous dot denotes a float literal. You’d explicitly call the method by using the syntax (2).+(2).

The ambiguous floating point syntax will however be deprecated in 2.10:

scala> 2.+(2)
<console>:1: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       2.+(2)
       ^
<console>:2: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
              2.+(2)
              ^
<console>:8: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
              2.+(2)
              ^
res1: Double = 4.0
like image 173
Debilski Avatar answered Nov 03 '22 10:11

Debilski