Scala _ wildcard

Few episodes ago we talked about _ in a context of use cases that I described as placeholder.

Now, let's see the other big group of use cases that is the wildcard or the I don't care category.

Let's review each of the use cases one by one

The first one is one that we have seen before in pattern matching, it is the default or wildcard match. Which is the match that match everything. Most of the time, it is used to catch errors or implement a default behavior when all the other matches have failed. Usually, you might want to put a value name instead of _ so that you can include what has failed in your error message.

The second one is to match some kind of structure, in this case, match on any Some and we don't care what is inside. As always, you could replace the _ by some value name to be able to do something with what is inside, but if you don't care, you can use the _ syntax.

Next one is related to the previous one, but with case class this time. We talked about unapply before. And so you might understand that the example with Some(_) is actually the same as the CaseClass(_, _, ...). It basically, ignore some of the return elements of the unapply method.

Number 4 is related to imports. It allows you to import everything under a specific package path. Same idea, if you do not care to include specific things, you include it all.

Number 5 , even tho it doesn't look like it, is also related. In fact, val behave like a pattern matching structure. We are going to see this more into details in a following episode.

Number 6 is similar as well, but the val is hidden inside the for-comprehension. It allows you to handle method that return Unit and still be able to include it inside the structure.

Number 7 is similar, it allows you to create behavior that ignores the input.

As you can see, _ can be used when you want to not care about a particular output.

Reveal more information and clues
Load Exercise