scala

In Scala, how would I update specific items in a Seq using a filter?


I have a Seq of objects (protobuf objects). I would like to iterate through the list, where a specific field value is filtered, and update these specific objects in the original list.

For example:

val serversProto = Seq(...)

serversProto = serversProto
  .filter(server => server.registrationStatus == "REGISTERED")
  .map(server => 
    ... update server object
  )

The problem with the above is that serverProtos is now a filtered list ONLY containing items that matched the filter. What I want to do is update the items in serversProto where the filter is true, but keep all the other original items.

Is this possible?


Solution

  • There is a few option, one of the option is more easy to understand, like Mateusz Kubuszok told above.

    1. Using map with IF - ELSE,
        val withMap = serversProto.map(server => 
          if (server.registrationStatus == "REGISTERED") {
            server.copy(name = s"${server.name}-updated")
          } else {
            server
          }
        )
    
    1. Using map with Pattern Matching
        val withPatternMatch = serversProto.map {
          case server if server.registrationStatus == "REGISTERED" =>
            server.copy(name = s"${server.name}-updated")
          case server => server
        }
    
    1. Using collect
        val withCollect = serversProto.collect {
          case server if server.registrationStatus == "REGISTERED" =>
            server.copy(name = s"${server.name}-updated")
          case server => server
        }
    

    But I recommend using no. 3, because its more clean and simple and more idiomatic in scala