Sealerate is a small (3rd-party-dependency-free) library that provides convenience
functions values[T]
and collect[T]
that dynamically create a set of all instances
of a sealed class.
Sealerate is available for Scala 2.10, 2.11, 2.12, and 2.13. If you are using sbt, add
the following to your build.sbt
:
libraryDependencies += "ca.mrvisser" %% "sealerate" % "0.0.6"
package example
import ca.mrvisser.sealerate
sealed trait Switch
object Switch {
case object On extends Switch
case object Off extends Switch
/**
* Enumerate all instances of of the [[Switch]] trait
*/
def values: Set[Switch] = sealerate.values[Switch]
}
Now Switch.values
will provide Set(On, Off)
, and will update automatically
when new objects are added.
Note that a compilation error is thrown if the following conditions aren't met:
- The given type
T
is not a sealed trait, sealed abstract class or sealed class - The case instances of type
T
are not allcase object
s. (As an alternative thecollect[T]
function will simply filter outcase class
s instead of throw an error)
- Branden Visser (core maintainer)
- jibbers42 (Scala 2.12 support)
- Philippus Baalman (Scala 2.12 & 2.13 support)
- Travis Brown (library based on his StackOverflow post)