I am studying some scala code and found this method which baffles me. In the match statement, what is the sublist@ construct? what kind of value does it contains? when I printed it its no diff than tail, but if I replace it with tail, the function returns diff result. Can somebody explain what it is and point me to a right resource to understand it? (I know I can search in google, but don’t know what to look for..)
def flatMapSublists[A, B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
ls match {
case Nil => Nil
case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
}
I would call it the “eat your cake and have it too operator”. At any level in pattern matching, you can give a part a name (before the @) and deconstruct it further (after the @). For instance imagine you want to match against a List with 3 elements, you need the second element, but you want to log the whole list:
Without this feature, you had to write something like
As you can see, we need to name the first and third element, just because we need them to get a list with the same structure on the right side, which is boilerplate. It is much easier and clearer if you can give the whole thing a name (
list), and parts deeper in the structure as well (elem), when you need both on the right side.