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?
There is a few option, one of the option is more easy to understand, like Mateusz Kubuszok told above.
val withMap = serversProto.map(server =>
if (server.registrationStatus == "REGISTERED") {
server.copy(name = s"${server.name}-updated")
} else {
server
}
)
val withPatternMatch = serversProto.map {
case server if server.registrationStatus == "REGISTERED" =>
server.copy(name = s"${server.name}-updated")
case server => server
}
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