Scala _ wildcard

Few episodes ago we talked about_in a context of use cases that I described asplaceholder.

Now, let's see the other big group of use cases that is thewildcardor theI don't carecategory.

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 thedefaultorwildcardmatch. 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 anySomeand 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 aboutunapplybefore. And so you might understand that the example withSome(_)is actually the same as theCaseClass(_, _, ...). It basically, ignore some of the return elements of theunapplymethod.

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

Number 5 , even tho it doesn't look like it, is also related. In fact,valbehave like apattern matchingstructure. We are going to see this more into details in a following episode.

Number 6 is similar as well, but thevalis hidden inside thefor-comprehension. It allows you to handle method that returnUnitand 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