Frage

I have a trait which will have a finite number of subclasses. At first I used the sealed modifier and defined the trait and all its subclasses in the same file. After the classes grew, I decided I wanted to refactor them into separate files, however once I did this I could no longer use the sealed modifier on the trait due to the constraint that all subclasses of a sealed trait must be in the same file.

In Scala, Is there a similar way to have a finite number of subclasses for a trait within the same package, across separate files while still gaining the compile-time advantages of sealed traits when doing exhaustive pattern matching?

War es hilfreich?

Lösung

Sealing is the only way to ask for exhaustiveness checking. However, you could define package-private traits AGuts, BGuts, CGuts, etc. in separate files and then in one file create sealed subclasses A, B, C, etc. as you did before, but mixing in those guts defined elsewhere.

sealed abstract class Thing
class A extends Thing with AGuts
class B extends Thing with BGuts
...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top