Combating Fallacy in Scala: Part 1
Join the DZone community and get the full member experience.Join For Free
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, and some concepts that we might not know. So, this series is all about exploring Scala and Combating Fallacy in Scala.
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.
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.
Stay tuned for the next parts.
Published at DZone with permission of Muskan Gupta. See the original article here.
Opinions expressed by DZone contributors are their own.
Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
File Upload Security and Malware Protection
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
How Agile Works at Tesla [Video]