Search code examples
scalacollectionsvectorimmutabilitytrie

How do I remove an element from a Vector?


This is what I'm doing now:

  private var accounts = Vector.empty[Account]

  def removeAccount(account: Account)
  {
    accounts = accounts.filterNot(_ == account)
  }

Is there a more readable solution? Ideally, I'd like to write accounts = accounts.remove(account).


Solution

  • I'd use this:

    accounts filterNot account.==
    

    Which reads pretty well to me, but ymmv. I'd also like a count that doesn't take a predicate, but the collection library is really lacking in specialized methods where one with a predicate can generalize the operation.

    Until 2.8.x, there was a - method, which got deprecated, iirc, because of semantic issues. It could actually have come back on 2.10 if my memory is serving me right, but it didn't. Edit: I checked it out, and saw that - is now reserved for a mutable method that modifies the collection it is applied on. I'd be all in favor of -:/:- though on sequences, where it makes sense to drop the first or last element equal to something. Anyone willing to front a ticket for that? I'd upvote it. :-)