列出所有扩展特征的案例对象

时间:2019-06-18 09:49:45

标签: scala

我正在尝试使用enum.valuestrait方法复制case object。例如,对于常规的enum,您可以执行以下操作:

object Permission extends Enumeration {
  type Permission = Value
  val SOME_THINGS, EVERYTHING = Value
}

val allEnumValues: Set[Permission] = Permission.values

我需要为每个Permission添加逻辑以验证用户是否应该拥有它,因此我试图使用traitcase 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]方法?

0 个答案:

没有答案