Reputation: 579
I have a collection col
with elements of type Foo
.
Foo
has a var bar
, which I need to change for every element in the collection.
Currently my code looks like this
col.map(baz => {
baz.bar = <something>
baz
})
Is there a nicer way to do this? I feel like this could be done with a one liner.
Upvotes: 2
Views: 43
Reputation: 48400
foreach
is designed for side-effects like that
col.foreach(_.bar = <something>)
after this col
will have all elements mutated. If you wish to avoid Unit
return type try chaining
import util.chaining._
col.map(_.tap(_.bar = <something>))
or other way around
col.tap(_.foreach(_.bar = <something>))
Idimoatic approach would be to avoid var
and have immutable case class Foo
then copy
col.map(_.copy(bar = <something>))
Upvotes: 4