Scala运算符奇怪

Luk*_*asz 14 scala

当我在2上调用+时,我得到了一个Int,但是当使用显式方法调用完成时,我得到了Double.

scala> 2+2
res1: Int = 4

scala> 2.+(2)
res2: Double = 4.0
Run Code Online (Sandbox Code Playgroud)

看起来.+()是在隐式转换为Int到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.+
                ^
Run Code Online (Sandbox Code Playgroud)

为什么会这样 ?

Deb*_*ski 20

在Scala 2.9和之前,2.被解释为2.0模糊点表示浮点文字.您可以使用语法显式调用该方法(2).+(2).

然而,不明确的浮点语法将在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
Run Code Online (Sandbox Code Playgroud)


om-*_*nom 16

原因不在于显式方法调用 - 通过编写2.+左侧指定Double然后在其上调用加法运算符:

scala> 2.
res0: Double = 2.0
Run Code Online (Sandbox Code Playgroud)