Skip to content

Instantly share code, notes, and snippets.

@ZviMints
Last active May 15, 2023 17:00
Show Gist options
  • Save ZviMints/ef20c383ae5e15388382828ddc05256d to your computer and use it in GitHub Desktop.
Save ZviMints/ef20c383ae5e15388382828ddc05256d to your computer and use it in GitHub Desktop.
FlaggedEnum
sealed case class BrandSafetyFeatureStatus(override val value: Long) extends FlaggedEnum[BrandSafetyFeatureStatus]
object BrandSafetyFeatureStatus extends enumeratum.Enum[BrandSafetyFeatureStatus] {
object Inclusion extends BrandSafetyFeatureStatus(1L << 0)
object Exclusion extends BrandSafetyFeatureStatus(1L << 1)
object Exception extends BrandSafetyFeatureStatus(1L << 2)
override def values: IndexedSeq[BrandSafetyFeatureStatus] = findValues
}
object Main extends App {
// parameters
// ✅
val featureStatus: BrandSafetyFeatureStatus = BrandSafetyFeatureStatus.Inclusion | BrandSafetyFeatureStatus.Exclusion
println(featureStatus)
println(featureStatus.hasFlag(BrandSafetyFeatureStatus.Exception))
println(featureStatus.hasFlag(BrandSafetyFeatureStatus.Inclusion))
println(BrandSafetyFeatureStatus.Inclusion)
println(BrandSafetyFeatureStatus.Inclusion & BrandSafetyFeatureStatus.Exclusion)
// exhaustiveness check
// ✅
def exhaustivenessCheck(featureStatus: BrandSafetyFeatureStatus): Unit = featureStatus match {
case BrandSafetyFeatureStatus.Inclusion => ???
}
// look up all values
// ✅
println(BrandSafetyFeatureStatus.values)
// look up value by name
// ✅
println(BrandSafetyFeatureStatus.withName("Inclusion"))
println(BrandSafetyFeatureStatus.withNameOption("X"))
println(BrandSafetyFeatureStatus.withNameOption("Exclusion"))
}
trait FlaggedEnum[T <: FlaggedEnum[T]] extends enumeratum.EnumEntry { self: { def copy(v: Long): T } =>
val value: Long
def | (other: T): T = copy(value | other.value)
def & (other: T): T = copy(value & other.value)
def hasFlag(flag: T): Boolean = (value & flag.value) == flag.value
// ...
override def toString: String = Option(getClass.getSimpleName).filter(_.endsWith("$")).fold(value.toString) { _.stripSuffix("$") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment