joel
joel

Reputation: 7867

Iterate over imported scala 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.

Upvotes: 1

Views: 97

Answers (1)

pedrorijo91
pedrorijo91

Reputation: 7845

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

}

Upvotes: 1

Related Questions