7
votes

This is the implementation of flatMap in Scala

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 ?

3

3 Answers

14
votes

++= can mean two different things in Scala:

1: Invoke the ++= method

In your example with flatMap, the ++= method of Builder takes another collection and adds its elements into the builder. Many of the other mutable collections in the Scala collections library define a similiar ++= method.

2: Invoke the ++ method and replace the contents of a 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 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).

3
votes

Note that ++= is a method, not a part of the Scala language. 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.

1
votes

The API of Builder says:

adds all elements produced by a TraversableOnce to this growable collection.