gpt4 book ai didi

scala - 在 Scala 中,a += b 何时变为 a = a + b?

转载 作者:行者123 更新时间:2023-12-04 01:03:36 25 4
gpt4 key购买 nike

Scala 只是有时会脱糖

a += b


a = a + b

但不总是。例如,一些可变集合定义了一个 +=方法,而是变成
a.+=(b)

这是行为吗
  • 完全取决于是否有合适的+=方法在 a ? (包括这种行为还有其他例子吗?)
  • 与对象是 val 还是 var 无关?

  • 相关例子

    改编自 Scala 编程,在
    var s = Set("a", "b")
    s += "c"

    In this case, the second line of code s += "c" is essentially shorthand for:


    s = s + "c"

    最佳答案

    When does a += b become a = a + b in Scala?


    当没有适用时 +=方法,有一个适用的 +方法和 a是可赋值的(也就是说,它是一个 var 或者有一个 a_= 方法)。
    或作为 the spec说:

    The re-interpretation occurs if the following two conditions are fulfilled.

    1. The left-hand-side l does not have a member named +=, and also cannot be converted by an implicit conversion to a value with a member named +=.
    2. The assignment l = l + r is type-correct. In particular this implies that l refers to a variable or object that can be assigned to, and that is convertible to a value with a member named +.


    Is this behaviour

    1. entirely determined by whether there is a suitable += method on a?
    2. independent of whether the objects are val or var?

    不完全的。如果有合适的 +=方法,它将被调用而不管任何其他因素(例如 a 可分配)。但是当没有时,其他因素决定了它是脱糖还是您收到错误消息。
    请注意,您收到的错误消息与从脱糖版本中获得的错误消息不同:当脱糖标准不适用时,您会收到一条错误消息,告诉您“+= 不是 .. .”,并解释为什么不能应用脱糖(例如“接收器不可分配”或您从 a + b 得到的类型错误,如果 a + b 会产生类型错误)。

    关于scala - 在 Scala 中,a += b 何时变为 a = a + b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51952060/

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