Can I match an entire Scala Object
by matching on a field of that object ?
Imagine, I have a trait Command
having a field def name: String
. I have several objects of this trait. Ls
, Cd
, Mkdir
, Echo
etc. Each of these objects have a specific string bound to name
.
e.g.
Mkdir.name = "mkdir", Cd.name = "cd".
Now, I receive a string from external system call it: input
. I want to match this string to get one of these objects. Only that I don't want multiple case clauses, one for each object. This is because, I'm running validations for different subset(s) of these commands.
My code looks like this:
input match {
case o @ (Mkdir.name | Cd.name | Rm.name) => // Some common code to run and return the matched Command (not string)
...
}
The problem is that, within each case, I need to know which Command's name was matched by the input. I can't know this with this code since here I'm only matching a string to a union of strings thereby here losing the context of what object (Command) that matched string was a part of.
So, ultimately my question is that can I match an object by matching on one of it's field?
getCommandByName
on this method you write all the matches one by one. And then you use this method on all other parts. – Luis Miguel Mejía Suárez