Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I call += with a single parameter on a Scala Set?

Tags:

scala

The mutable Set has a method def +=(elem1: A, elem2: A, elems: A*): Set.this.type but I can call this method with a single paramter:

val s = scala.collection.mutable.Set(1, 2)
s += 4

What method is actually called? There seems to be no overload for += with a single parameter. What is the intention of the above method signature?

like image 443
deamon Avatar asked Sep 19 '13 14:09

deamon


People also ask

What does ++ mean in Scala?

The effect of = can also be used to easily understand what ++= would do. Since ++ generally represents concatenation of two collections, ++= would mean an "in place" update of a collection with another collection by concatenating the second collection to the first.

What is difference between set and list in Scala?

A set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure.

Does Scala pass by reference or value?

In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).


1 Answers

Well, a little investigation here:

scala> val s = scala.collection.mutable.Set(1,2)
s: scala.collection.mutable.Set[Int] = Set(1, 2)

scala> s += 4
res0: s.type = Set(1, 2, 4)

scala> s +=
<console>:9: error: missing arguments for method += in trait SetLike;
follow this method with `_' if you want to treat it as a partially applied funct
ion
              s +=
                ^

Oh, OK, so let's find the trait SetLike docs:

abstract def +=(elem: A): SetLike.this.type

Adds a single element to the set.

And now it's clear it's an implementation of an abstract method in the mutable.SetLike trait.

like image 161
Patryk Ćwiek Avatar answered Nov 02 '22 12:11

Patryk Ćwiek