我正在尝试使用enum.values
和trait
方法复制case object
。例如,对于常规的enum
,您可以执行以下操作:
object Permission extends Enumeration {
type Permission = Value
val SOME_THINGS, EVERYTHING = Value
}
val allEnumValues: Set[Permission] = Permission.values
我需要为每个Permission
添加逻辑以验证用户是否应该拥有它,因此我试图使用trait
和case object
方法。使用这种方法,枚举将变为:
trait Permission {
def name: String
def appliesTo(user: User): Boolean
}
object Permission {
def values: Set[Permission] = ... // Can I use reflection here?
case object SOME_THINGS extends Permission {
override def name: String = "SOME_THINGS"
override def appliesTo(user: User): Boolean = user.isTeamMember
}
case object EVERYTHING extends Permission {
override def name: String = "EVERYTHING"
override def appliesTo(user: User): Boolean = user.isAdmin
}
}
如何使用反射来获取扩展Permission
的案例对象列表,从而实现我的def values: Set[Permission]
方法?