不可变集合上的 += 运算符 [英] the += operator on immutable Set

查看:57
本文介绍了不可变集合上的 += 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时:

var airlines = Set("Qantas", "JetStar", "Air NZ")
airlines += "Virgin"

航空公司是一个不可变的集合.

airlines is an immutable Set.

+= 未在不可变 Set trait 上定义.

+= is not defined on the immutable Set trait.

那么 += 是 Scala 中的内置运算符吗?我的意思是 scala 怎么知道用新的 set("Qantas", "JetStar", "Air NZ", "Virgin") 重新分配航空公司?

So is += a built-in operator in scala? I mean how does scala know to reassign airlines with a new set("Qantas", "JetStar", "Air NZ", "Virgin") ?

推荐答案

如果使用了以 = 结尾的运算符(例如 +=)但未在类上定义, Scala 编译器会将其脱糖为 eg

If an operator ending with = (e.g. +=) is used but not defined on a class, the Scala compiler will desugar this into e.g.

airlines = airlines + "Virgin"

或者,对于++=,我们有

airlines ++= airlines

脱糖

airlines = airlines ++ airlines

当然,作为 dmeister 注释,这只会编译如果这个新表达有意义.例如,如果我们处理 vars.

Of course, as dmeister notes, this will only compile if that new expression makes sense. For example, if we deal with vars.

请参阅 Scala 参考 §6.12.4 赋值运算符
(<= , >=!= 被排除在特殊情况之外,模式也以 开头=.)

See Scala Reference §6.12.4 Assignment Operators
(<= , >= and != are excluded as special cases, as are patterns also starting with =.)

这篇关于不可变集合上的 += 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆