user462455
user462455

Reputation: 13588

Update method in mutable HashSet class in Scala

HashSet class in Scala's mutable collections supports update method.

However, name update seems counter-intuitive(to me atleast). From the documentation here it says

This method allows one to add or remove an element elem from this set depending on the value of parameter included. Typically, one would use the following syntax: set(elem) = true

I tried using update on scala console. When I called update(elem, true) instead of updating elem with new version, it just did nothing when the element was present.

When update(elem, false), it removed the elem.

My question is what is the purpose of update method as it is not updating anything

Upvotes: 1

Views: 355

Answers (1)

Ende Neu
Ende Neu

Reputation: 15783

I think the update is intended on the set and not on the elements in the set (it doesn't make sense to "update" an element, it only makes sense for collections which have a key-value relationship), and in fact if you look at the source code, this method does update the set:

def update(elem: A, included: Boolean) {
  if (included) this += elem else this -= elem
}

So basically you can use the included variable to tell wether to add or remove an element, in your case adding twice the same element doesn't give you any update because a set doesn't allow duplicates.

Why one would use update instead of add or remove it's outside my comprehension.

Upvotes: 3

Related Questions