Rao
Rao

Reputation: 153

Update case class data in an array

I am trying to update case class from an array.
Trying to update case class data inside an array, but I have to remove older record as well

I have tried as below

case class Data(str1: String, str2:String) { def updateMsg(msg : String) = this.copy(str2 = msg)}
val list = Array(Data("1", "2"), Data("2", "b"), Data("3", "c"))
list :+ list.filter(_.str1.equalsIgnoreCase("1"))(0).updateMsg("a")

I got results from above list as below

Array[Data] = Array(Data(1,2), Data(2,b), Data(3,c), Data(1,a))

Is there any better way to update existing case class row ?

Upvotes: 0

Views: 131

Answers (1)

Tim
Tim

Reputation: 27421

A simple map should do it:

list.map { data =>
  if (data.str1.equalsIgnoreCase("1")) {
    data.updateMsg("a")
  } else {
    data
  }
}

or

list.map {
  case data if data.str1.equalsIgnoreCase("1") =>
    data.updateMsg("a")
  case data =>
    data
}

Upvotes: 2

Related Questions