collectFirst: Applying partial function with multiple case clauses

175 Views Asked by At

So I have defined a partial function to be used for collectFirst method in collection:

myList.collectFirst{
  case A(_,_,_) => ....
  case B(_,_,_) => ....
  case C(_,_,_) => ....
}

If myList contains A,B,C all then which case would be executed?

1

There are 1 best solutions below

0
Bondarenko On BEST ANSWER

The documentation for collectFirst said the following:

Finds the first element of the collection for which the given partial function is defined, and applies the partial function to it.

Let's assume val myList = List(A(...), B(...), C(...)). In that case case A(_, _, _) will be executed. If we have val myList = List(B(...), A(...), C(...)) then the second case will be executed because B(...) is the first element satisfied the partial fucntion.