2

Combating Fallacy in Scala: Part 1

 3 years ago
source link: https://blog.knoldus.com/combating-fallacy-in-scala-part-1/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK