9

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 Answers 3

19

++= 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).

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

The API of Builder says:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.