简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM