0

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 ?

2
  • @TomerShetah :1. Whenever I do an update in case class data I have to update the existing row [But In my case instead of updating row I am creating a new row with updated values]. 2. I am using scala 2.11 version, could please suggest me instead array what will I have to use.
    – Rao
    Commented Sep 3, 2020 at 6:07
  • 2
    I would recommend you to use Lists or any other concrete immutable collection, instead of plain Arrays. Commented Sep 3, 2020 at 12:31

1 Answer 1

2

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
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.