[英]What does “++=” mean in Scala
This is the implementation of flatMap
in Scala 这是Scala中
flatMap
的实现
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { def builder = bf(repr) // ... val b = builder for (x <- this) b ++= f(x).seq b.result }
What does ++=
mean here ? ++=
意味着什么?
++=
can mean two different things in Scala: ++=
可以表示Scala中的两个不同的东西:
1: Invoke the ++=
method 1:调用
++=
方法
In your example with flatMap
, the ++=
method of Builder
takes another collection and adds its elements into the builder. 在使用
flatMap
的示例中, Builder
的++=
方法采用另一个集合并将其元素添加到构建器中。 Many of the other mutable collections in the Scala collections library define a similiar ++=
method. Scala集合库中的许多其他可变集合定义了类似的
++=
方法。
2: Invoke the ++
method and replace the contents of a var
2:调用
++
方法并替换var
的内容
++=
can also be used to invoke the ++
method of an object in a var
and replace the value of the var
with the result: ++=
也可用于调用++
的对象的方法,在var
和替换的值var
与结果:
var l = List(1, 2)
l ++= List(3, 4)
// l is now List(1, 2, 3, 4)
The line l ++= List(3, 4)
is equivalent to l = l ++ List(3, 4)
. 行
l ++= List(3, 4)
等价于l = l ++ List(3, 4)
。
Note that ++=
is a method, not a part of the Scala language. 请注意,
++=
是一种方法,而不是Scala语言的一部分。 If it is defined for a particular class, then it has whatever meaning that class defines it to have. 如果它是为特定类定义的,那么它具有类定义它具有的任何含义。 In this case it means "add these to the end."
在这种情况下,它意味着“将这些添加到最后”。
Also note that if a class defines ++
but not ++=
then the compiler will treat 还要注意,如果一个类定义
++
但不定义++=
那么编译器将会处理
x ++= y
as 如
x = x ++ y
this is true generally for symbols ending in an equal sign (other than ==
, !=
, and =
, of course). 对于以等号结尾的符号(当然,除了
==
, !=
和=
)通常都是如此。 This syntactic sugar allows immutable and mutable variants of the same data structure to be used in a consistent way. 这种语法糖允许以一致的方式使用相同数据结构的不可变和可变变体。
The API of Builder says: Builder的API说:
adds all elements produced by a TraversableOnce to this growable collection.
将TraversableOnce生成的所有元素添加到此可扩展的集合中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.