Combating Fallacy in Scala: Part 1

Combating Fallacy in Scala
Reading Time: 3 minutes

Hi everyone, I am going to start a blog series related to Scala. This is going to be a bit different as it focuses on things such as some mistakes that we usually do, unknowingly or some concepts that we might not know. So this series is all about exploring Scala and Combating Fallacy in Scala. if you want to be a part then stay here and read further.

So for the first part, the topic is “Matching with Multiple Conditions”

Matching with Multiple Conditions

Before looking into this you should have an idea about Pattern Matching.

According to Scala Docs “Pattern matching is a mechanism for checking a value against a pattern.”

In pattern matching, we try to find a perfect match/ the condition that suits the variable/collection/constant against which we are matching.

For example, consider the following:

In the example, we are matching against the single case at a time. But, what if we want to match against multiple cases at a time? How will we do that?

The solution to that is using “|”(pipe) operator.

Let’s consider a scenario where you want to check if the user input is a String or an Int. If it is String or Int then it’s a perfect match else not. Now, I’ll give you the options for how can we do this and you should pick the correct option.

Option 1

Option 2

What do you think? Should both of them work or is there any issue with one of them?

Time to Reveal

The correct option is Option 2. But why?

So the reason is Scala does not allow bound variables when we are using “|”(pipe) operator. In the first option “value” is a bound variable and therefore there will be a compilation error as following:

If it is important for you to get the value too, you will have to make different cases. In this case, the solution will be as follows:

That’s it for the Fun Scala: Part 1. I hope this was helpful 😁

Also, here is the second part Combating Fallacy in Scala: Part 2.

Stay tuned for next parts.

Knoldus-blog-footer-image

Written by 

Muskan Gupta is a Software Consultant having almost 1-year experience. She has knowledge of languages like C, C++, Java and Scala. She is familiar with Object-Oriented Programming Paradigms and also has an interest in relational database technologies. Her hobbies include travelling, reading novels and listening to music.

1 thought on “Combating Fallacy in Scala: Part 13 min read

Comments are closed.