14

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 ?

0

2 Answers 2

20

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 
Sign up to request clarification or add additional context in comments.

2 Comments

BTW, why there are three warnings?
Don’t know. But of course it is still a snapshot (and a self-compiled one).
16

The reason is not in explicit method call -- by writing 2.+ you specifying Double on the left side and then calling addition operator on it:

scala> 2. res0: Double = 2.0 

1 Comment

That is strange, glad they depracate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.