1

I want to safely be able to get an enum based on the value.

object UserType extends Enumeration {
  type UserType = Value
  val Anonymous, Member, Paid = Value
}

If I do:

UserType(100)

I get an error:

java.util.NoSuchElementException: key not found: 100
  at scala.collection.MapLike$class.default(MapLike.scala:228)
  at scala.collection.AbstractMap.default(Map.scala:59)
  at scala.collection.mutable.HashMap.apply(HashMap.scala:65)
  at scala.Enumeration.apply(Enumeration.scala:114)
  ... 32 elided

Is there a typesafe way to do this?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

1 Answers1

0

You can try using find on the ValueSet of the Enum and then get an Option. If the value does not exists, you'll get a None value (using getOrElse is very convenient here).

Example:

UserType.values.find(_ == 100)

I would really recommend you to also read this answer that explains how to model a better type safe enums.

Community
  • 1
  • 1
Alon Segal
  • 818
  • 9
  • 20