Change the item in the list where the condition is true

case class Person(name: String, age: Int, qualified: Boolean = false)

val people: List[Person] = ....

val updated: List[Person] = people.map(person => 
  if (person.age >= 25) 
    person.copy(qualified=true) 
  else
    person  // unmodified
))

// Setting every person above 25 y.o. as qualified

Is there a combinator / higher order way? How:

people.updateWhere(_.age >= 25, _.copy(qualified=true))

It looks like a conditional map. Most elements go through unmodified ones, but those elements that satisfy the condition are modified / "displayed".

+4
source share
2 answers

As far as I know, there is no such thing, although you can do it through an implicit conversion:

implicit class ListOps[A](self: List[A]) extends AnyVal {
  def updateIf(predicate: A => Boolean, mapper: A => A): List[A] = {
    self.map(el => if (predicate(el)) mapper(el) else el)
  }
}

Test:

@ case class Person(name: String, age: Int, qualified: Boolean = false)
defined class Person
@  val people = List(Person("A", 3, false), Person("B", 35, false))
people: List[Person] = List(Person("A", 3, false), Person("B", 35, false))
@ people.updateIf(_.age >= 25, _.copy(qualified=true))
res3: List[Person] = List(Person("A", 3, false), Person("B", 35, true))
+1
source

Maybe I missed something, but this is just standard map. I would suggest a simple approach:

scala> case class Person(name: String, age: Int, qualified: Boolean = false)
defined class Person

scala> val people = List(Person("John", 25), Person("Frank", 30))
people: List[Person] = List(Person(John,25,false), Person(Frank,30,false))

scala> def qualifyIf(p: Person)(pred: Person => Boolean) = if (pred(p)) p.copy(qualified = true) else p
qualifyIf: (p: Person)(pred: Person => Boolean)Person

scala> people.map(qualifyIf(_)(_.age > 25))
res1: List[Person] = List(Person(John,25,false), Person(Frank,30,true))

qualifyIf - Person Person, .

, - , cats Scalaz, , .

+1

Source: https://habr.com/ru/post/1624278/


All Articles