如何建模类型安全的枚举类型?
3 月,跳不动了?>>> Scala没有像Java那样的类型安全 enum 。 给定一组相关常量,Scala表示这些常量的最佳方法是什么? #1楼 您可以使用密封的抽象类而不是枚举,例如: sealed abstract class Constraint(val name: String, val verifier: Int => Boolean) case object NotTooBig extends Constraint("NotTooBig", (_ < 1000)) case object NonZero extends Constraint("NonZero", (_ != 0)) case class NotEquals(x: Int) extends Constraint("NotEquals " + x, (_ != x)) object Main { def eval(ctrs: Seq[Constraint])(x: Int): Boolean = (true /: ctrs){ case (accum, ctr) => accum && ctr.verifier(x) } def main(args: Array[String]) { val ctrs = NotTooBig :: NotEquals(5) :: Nil val evaluate =