Last active
May 15, 2023 17:00
-
-
Save ZviMints/ef20c383ae5e15388382828ddc05256d to your computer and use it in GitHub Desktop.
FlaggedEnum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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