Scala operator oddity

北城余情 提交于 2019-12-17 20:43:40

问题


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 ?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/9655080/scala-operator-oddity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!