Refactoring and output data

The foldRight method has the following signature:

foldRight[B](z: B)(op: (A, B) => B): B

Its first parameter is the accumulator value, its second parameter is the function that combines one element of the list with the accumulator. As you can see, that function takes two parameters.

Our list contains Strings and the value for z is the tuple of two empty lists, so the function op is given a String and a tuple (List[...], List[...]). With normal lambda syntax, we could write:

caseIDsList.foldRight(List.empty[...], List.empty[...])(
  (idCase, bothLists) =>
    readSinglePair(idCase, mFolder, bName) match {
      case None =>          (idCase :: bothLists._1,           bothLists._2)
      case Some(result) =>  (          bothLists._1, result :: bothLists._2)
    }
)

As you can see, this is less clear, as our lists don’t have meaningful names. One way to make it better would be an extra line

val (invalid, valid) = bothLists

Such assignments actually do a pattern match under the hood, and we could rewrite this as

(idCase, bothLists) match {
  case (idCase, (invalid, valid)) => ... rest of function ...
}

Of course, matching the other parameter idCase is not necessary, but when your lambda consists of only a match over the whole parameter list (which is matched like a tuple, if there is more than one parameter), as this happens frequently Scala offers shortened syntax.
The line case (idCase, (invalid, valid)) => uses this shortened syntax and is equivalent to (id, lists) match { case (idCase, (invalid, valid)) => .... }

In other words, it is a shorthand to give the elements of the tuple, which is our second parameter, useful names.

By the way, the code you tried in your REPL uses the same syntax, partitionMap also expects a function, and you wrote it using case without a match. As you can see there, it is also possible to use this with multiple cases.

Note, that if your match is not exhaustive (i.e. there are possible values that wouldn’t match any case), you will get a PartialFunction, which may cause a MatchError at runtime when called with wrong parameters.

1 Like

@crater2150
Thank you very much for the explanation: it is clearer now.
Best regards

Sorry @crater2150 , it was you who tells about about the Scala version :wink: .
Again, thank you a lot @cbley , @crater2150 , @Iltotore, @jducoeur for you help and advices.
I managed to refactor several methods of my classes and improve the quality of my codes.
Best regards