1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This helped me a lot, however, trying to use your Find solution, the function returns Some(Person(...)) and not Person(...) as it should. What tweak should I do to accomplish what I want?
What it returns is an option, if you are sure you can always find an element from the list that satisfies your predicate, then you can use get method to get the Person like totalPersons.find(_.workstations.contains(ws)).get, if you are not sure, use getOrElse(...) to return a default value if the element is not found.
Perfect. Thanks.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.