Scala val pattern matching

Let's see how pattern matching appear in other aspect of the language.

More specifically, how it shows up in val assignment.

Using pattern matching in conjunction with val can be very useful especially when working with Tuple or other structures such as Option.

It allows you to extract only the part you need and leave behind the rest using the _ symbol.

However, you have to be extremely careful using pattern matching with val because you don't have a case _ => to catch the not matched cases. Which means, you are going to trigger exception at runtime.

In the last example, if you give anything different than abc, the code is going to fail. But this failure happens at runtime, not at compile time which can be extremely bad and dangerous.

Use this carefully !

Reveal more information and clues
Load Exercise