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?

11
  • But why won't you create class, and then make objects at runtime? Commented Oct 21, 2016 at 16:14
  • Because you cannot do pattern matching on instances of a class, especially exhaustive pattern matching. Commented Oct 21, 2016 at 16:18
  • What about pattern matching by some property of class? Create objects with pattern on property, and then match them by that property Commented Oct 21, 2016 at 16:20
  • 1
    It is possible with scala macros. Commented Oct 21, 2016 at 16:21
  • @KamilBanaszczyk Then that property has to be a bunch of case object, otherwise the matching won't be exhaustive Commented Oct 21, 2016 at 16:28

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.