0

I have those classes like this:

object Class1 extends parent {
   def execute() {
        print("Class1")
   }
}
object Class2 extends parent {
   def execute {
        print("Class2")
   }
}

Then I have a Runner like this:

object Runner extends runParent {
    def manageRun(className: String) = {
        def ClassInstance = className match {
             case Some("Class1") => Some(Class1)
             case Some("Class2") => Some(Class2)
        }
       ClassInstance.execute()
    }
}

There is any way to change this managerRun code and when I create a Class3 I don't need to add a new case in the match?

Thanks!

Oli
  • 9,766
  • 5
  • 25
  • 46
  • Could you explain a bit more the expected usage? Is the `className: String` parameter a requirement? – Gaël J Dec 28 '22 at 16:37
  • 2
    Possible, yes either using runtime reflection if you need to add classes dynamically or using macros if yo are okay with re-compiling. You may also use a code generator if everything is in the same project. - In general, I would advise doing neither of them; well maybe the last one, the cost of a little bit of boilerplate is not bigger than the clarity of reading the code. – Luis Miguel Mejía Suárez Dec 28 '22 at 16:39
  • I have a parameter file that sends a className as a string to my job, for example: "Class1" or "Class2" – Anderson Dutra Dec 28 '22 at 17:15
  • IMHO you should decorrelate the class name from the input string. And when you do that, you have no other choice than do to some kind of mapping like you already did. The callers should probably not know anything about how your classes are named. (I don't have the full context, it might be okay in some contexts but from what I see above, you just want a kind of "job name"). – Gaël J Dec 28 '22 at 18:05
  • I got it, I was just asking cause I don't know if exists a better answer, cause everytime i create a new class I need to add a case in this match – Anderson Dutra Dec 28 '22 at 19:26
  • 1
    https://stackoverflow.com/questions/73859222/ https://stackoverflow.com/questions/73990571/ https://stackoverflow.com/questions/34534002 https://stackoverflow.com/questions/13671734 https://stackoverflow.com/questions/69556749 https://stackoverflow.com/questions/74082749/ https://stackoverflow.com/questions/23120585/ – Dmytro Mitin Dec 29 '22 at 03:32

0 Answers0