undisp
undisp

Reputation: 721

Scala: return element using if inside map function

I have a list of type Person in scala like this:

Person("P1", "Person 1", List(WorkStation 1, WorkStation 2))
Person("P2", "Person 2", List(WorkStation 1, WorkStation 3, WorkStation 4, WorkStation 5))
Person("P3", "Person 3", List(WorkStation 3, WorkStation 5))
Person("P4", "Person 4", List(WorkStation 2, WorkStation 4))

I want to code a function that receives this list and a parameter ws: WorkStation.WorkStation (it is a case object) and then I want that function to return the first element Person which has ws in it's list.

For example, if ws was Workstation 3 I wanted to return the list entry with Person 2.

I thought about doing something like this:

def setPerson(ws: WorkStation.WorkStation, totalPersons: List[Person]): Person = {
    totalPersons.map { p => if (p.workstations.contains(ws)) return p }
}

However, this doesn't compile, because it gives me an error and it is not the most functional approach for sure.

Can anyone help me?

Upvotes: 1

Views: 199

Answers (2)

pedrorijo91
pedrorijo91

Reputation: 7845

totalPersons.find(elem => elem.workstations.contains(ws))

or

totalPersons.find(_.workstations.contains(ws))

the 1st is more readable (specially for scala rookies), but the 2nd is common syntactic sugar used

Upvotes: 0

akuiper
akuiper

Reputation: 214927

You can use collectFirst:

totalPersons.collectFirst{ case p if p.workstations.contains(ws) => p }

Or find:

totalPersons.find(_.workstations.contains(ws))

See here for more information.

Upvotes: 2

Related Questions