2

In my current project, I need to define a lot of case objects subclassing a single sealed trait. The names of these objects have a pattern, e.g., Case1, Case2, Case3, ..., CaseN. I was wondering if there is way in scala to define all these case objects in a programmatical way, for example with a loop, instead of writing N lines of definitions.

If this is feasible, it would also be great to do this at compile time so that the case objects defined in this way are known to type checking. This sounds impossible in most languages (you can have either dynamically defined types like in python or have static type safety like in C/C++, but not both), but maybe it is doable in Scala for its powerful compile-time reflection?

uraj
  • 339
  • 1
  • 10

1 Answers1

1

I'm thinking about this solution:

trait customTrait{
  val property: String
}

case class toMatch(property: String) extends customTrait{
}

val cases: Seq[toMatch] = for{
  x <- 0 until 10
} yield toMatch("property" + x)

def matchCase(caseToMatch: customTrait): String = caseToMatch match{

  case toMatch("property1") => "1"
  case toMatch("property2") => "2"
  case toMatch("property3") => "3"
  case toMatch("property4") => "4"
  case _ => "non"

}

for {
  x <- cases
} yield matchCase(x)
Kamil Banaszczyk
  • 1,133
  • 1
  • 6
  • 23
  • This piece of code works, but like I mentioned it lacks static checking on the cases you wrote in the match block. If someone forgets to add a case for, say, "property3", the compiler won't issue a warning. On the other hand, if you leave out the wild card case, the compiler will always issue a warning. – uraj Oct 21 '16 at 16:54