gpt4 book ai didi

Scala 运算符的奇怪之处

转载 作者:行者123 更新时间:2023-12-03 21:10:38 29 4
gpt4 key购买 nike

当我在 2 上调用 + 时,我会返回一个 Int,但是当它使用显式方法调用完成时,我会得到 Double。

scala> 2+2
res1: Int = 4

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

似乎 .+() 是在隐式转换为 Double 的 Int 上调用的。
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.+
^

为什么呢 ?

最佳答案

在 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

关于Scala 运算符的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9655080/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com