sh0hei
sh0hei

Reputation: 51

Update (or Replace) item(s) in immutable collection in Scala

What is best practice to update (or replace) a item in Seq ?

case class Minion(id: Int, name: String, motivation: Int)
val minions: Seq[Minion] = Seq(
  Minion(1, "Bob", 50),
  Minion(2, "Kevin", 50),
  Minion(3, "Stuart", 50))

I'd like to acquire new Collection

Seq(
  Minion(1, "Bob", 50),
  Minion(2, "Kevin", 50),
  Minion(3, "Stuart", 100))

What's best way ?

Upvotes: 1

Views: 805

Answers (2)

Dima
Dima

Reputation: 40500

Map also works, and might be a little bit easier to read than updated:

minions.map {
  case Minion(2, name, n) => Minion(2, name, 100)
  case m => m
}

One benefit of this over updated besides readability is that you can modify several elements in one go.

Upvotes: 2

Tzach Zohar
Tzach Zohar

Reputation: 37822

Use updated:

// first argument is index (zero-based) - so using 2 to replace 3rd item:
scala> minions.updated(2, Minion(3, "Stuart", 100))
res0: Seq[Minion] = List(Minion(1,Bob,50), Minion(2,Kevin,50), Minion(3,Stuart,100))

Or, without repeating the unchanged attributes of the new Minion:

scala> minions.updated(2, minions(2).copy(motivation = 100))
res1: Seq[Minion] = List(Minion(1,Bob,50), Minion(2,Kevin,50), Minion(3,Stuart,100))

Upvotes: 6

Related Questions