bcr
bcr

Reputation: 950

Scala in-line append with comparison and loop

I am looking for the Scala syntax for appending to an ArrayBuffer using a comparison. I have two arrays of two different types so I cannot simply use an intersection. In essence this is what I am looking for:

val allPeople : ArrayBuffer[Person] = ...
val result = ArrayBuffer[Person]()
val acceptableAges : ArrayBuffer[Age] = ...

// Simplify below
for (p <- allPeople if acceptableAges.indexof(p.age) >= 0) 
    result.append(p)

Is there a sleek solution to this? New to Scala.

Upvotes: 0

Views: 151

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31252

Please avoid using mutable variables as much as you can(which takes time but question yourself everytime you see mutable var). There is scala and fp for a reason.

What you are looking for is a .filter function.

Here goes example,

scala> final case class Age(age: Int)
defined class Age

scala> final case class Person(name: String, age: Age)
defined class Person

Given:

scala> val allPeople = List(Person("prayagupd", Age(100)), Person("steven wilson", Age(200)))
allPeople: List[Person] = List(Person(prayagupd,Age(100)), Person(steven wilson,Age(200)))

scala> val acceptableAges : List[Age] = List(Age(100), Age(150))
acceptableAges: List[Age] = List(Age(100), Age(150))

use .filter to filter your data:

scala> allPeople.filter(p => acceptableAges.contains(p.age))
res2: List[Person] = List(Person(prayagupd,Age(100)))

Upvotes: 1

Related Questions