1

I am trying to replicate enum.values using the trait and case object approach. For example with a regular enum you can do:

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

val allEnumValues: Set[Permission] = Permission.values

I need to add logic to each Permission to validate if a user should have it, hence I am trying to use the trait and case object approach. Using this approach the enum becomes something like:

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
  }
}

How can I use reflection to get a list of case objects extending Permission and therefore implement my def values: Set[Permission] method?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Eduardo
  • 6,900
  • 17
  • 77
  • 121
  • 4
    Project [enumeratum](https://github.com/lloydmeta/enumeratum) does a similar thing to what you want to achieve, so maybe consider using it instead of creating own solution? – Krzysztof Atłasik Jun 18 '19 at 10:07
  • 1
    @KrzysztofAtłasik Looks good thanks for that! – Eduardo Jun 18 '19 at 10:20
  • 4
    Possible duplicate of [Iteration over a sealed trait in Scala?](https://stackoverflow.com/questions/13671734/iteration-over-a-sealed-trait-in-scala) – lprakashv Jun 18 '19 at 10:27

0 Answers0