当我在2上调用+时,我得到一个Int,但是当使用显式方法调用完成时,我得到了Double。
scala> 2+2
res1: Int = 4
scala> 2.+(2)
res2: Double = 4.0
似乎。在隐式转换的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.+
^
为什么会这样?
答案 0 :(得分: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
答案 1 :(得分:16)
原因不在于显式方法调用 - 通过编写2.+
,在左侧指定Double,然后在其上调用加法运算符:
scala> 2.
res0: Double = 2.0