Scala val pattern matching

Let's see howpattern matchingappear in other aspect of the language.

More specifically, how it shows up invalassignment.

Usingpattern matchingin conjunction withvalcan be very useful especially when working withTupleor other structures such asOption.

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 usingpattern matchingwithvalbecause you don't have acase _ =>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 thanabc, 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