score:2

Accepted answer

I'm not entirely sure what your actual goal is. I guess what you are trying to achieve seem to be better solved by filter and map:

  • filter serves as validator in this case, i.e., people.filter(isFirstNameValid). This returns a collection of all people with a defined first name -- is this what you want?
  • map serves as extractor of the desired field, in this case the first name. So overall people.filter(isFirstNameValid).map(_.firstName) in case you want your collection to represent first names instead of a complete person. If you furthermore want to convert from Option (of first name) to a concrete value you may want to use flatMap instead (this also makes the explicit validation unnecessary).

In case you really what to stick to a solution based on modifying external state, you have to place your mutable variable in an external scope for instance...


Related Query

More Query from same tag