【问题标题】:Shorthand arithmetic operators return different results in Scala - EG: 3 + 2 != 3.+(2) [duplicate]速记算术运算符在 Scala 中返回不同的结果 - EG:3 + 2 != 3.+(2) [重复]
【发布时间】:2012-08-08 05:07:35
【问题描述】:

可能重复:
Scala operator oddity

我对 Scala 很陌生,我读到在这种语言中,一切都是对象,很酷。此外,如果一个方法只有 1 个参数,那么我们可以省略 '.'和双亲'()',没关系。

因此,如果我们采用以下 Scala 示例:3 + 2,“3”和“2”是两个 Int 对象,“+”是一个方法,听起来不错。然后3 + 2 只是3.+(2) 的简写,这看起来很奇怪,但我还是明白了。

现在让我们比较REPL上的以下代码块:

scala> 3 + 2
res0: Int = 5

scala> 3.+(2)
res1: Double = 5.0

这里发生了什么?为什么显式语法返回Double,而简写返回Int??

【问题讨论】:

    标签: scala operators arithmetic-expressions


    【解决方案1】:

    3.Double。词法分析器首先到达那里。试试(3).+(2)

    【讨论】:

    • 是的,但请注意,如果您在 Scala 2.10 中键入 3.+(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.
    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 2017-05-20
    • 2018-04-02
    • 2013-06-04
    • 2017-06-29
    • 2023-03-20
    • 2016-08-07
    • 2019-02-22
    相关资源
    最近更新 更多