1
  • My scala program will be passed a list of numerical IDs on the command line
  • I have a package of ~500 classes, where each class has a numerical ID
  • I want to use only those classes whose IDs were passed on the command line
  • I want to do this without writing out the names of all ~500 classes

For example with directory

MyClasses
  - _001_first
  - _002_second
  - _003_third

where each class is sth like

class _001_first {val id = 1}

I'm looking for sth like

import MyClasses._

object Main extends App {
  val instances = for (
    MyClasses <- Class // I believe this is the problem line
    inst = Class()
    if args.contains(inst.id)
  ) yield inst
}

Is this possible? And if so, does anyone know the design decision behind why it's not possible? Suggestions for a completely different design are welcome

Context

I'm writing a test framework. Each test case will be in a separate file and I want to be able to specify on the command line which test cases to run.

joel
  • 6,359
  • 2
  • 30
  • 55
  • 2
    If you make your classes extend a common trait, then you can use the method described in this answer: https://stackoverflow.com/questions/34534002/getting-subclasses-of-a-sealed-trait – Dima Jan 13 '18 at 15:05

1 Answers1

1

your use case seems weird (do you want to explain the big picture?), but you can use reflection to get the class in runtime by it's name and search for the attribute.

using a common trait where the method is declared may be useful also (for instance, each class would implement

trait X {

 def id: Int

}
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82