Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "++=" mean in Scala

Tags:

scala

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 ?

like image 393
Michael Avatar asked Apr 02 '14 16:04

Michael


2 Answers

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

like image 142
wingedsubmariner Avatar answered Sep 18 '22 22:09

wingedsubmariner


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.

like image 23
AmigoNico Avatar answered Sep 19 '22 22:09

AmigoNico