ilansch
ilansch

Reputation: 4878

Check if certain string exist in my enum values without NoSuchElement Exception

I have the following code:

object Order extends Enumeration("asc", "desc") {
  type OrderType = Value
  val asc, desc = Value
  }

And i use it:

  val someStr:String = "someStr"
  val order = Order.withName(someStr)

This gives me the enum of the input string, but if i send string "asc1" i get Exception:

NoSuchElementException: None.get (ProductRequest.scala

My question is - Can i iterate the values and check if the strings exists? This way i can throw better detailed exception..

I was thinking i can iterate Order.values -> but could not find something useful

Thanks

Upvotes: 9

Views: 8094

Answers (2)

qed
qed

Reputation: 23104

This seems to do the trick:

object EnumerationTypes extends App {
  object Order extends Enumeration {
    type OrderType = Value
    val asc = Value("asc")
    val desc = Value("desc")
    def valueOf(name: String) = this.values.find(_.toString == name)
  }
  println(Order.valueOf("asc")) // Some(asc)
  println(Order.valueOf("ascending")) // None
}

It returns None when the string is not valid instead of throwing an exception.

Upvotes: 6

Lauri
Lauri

Reputation: 4800

Your could define your Enumeration as:

object Order extends Enumeration {
  type OrderType = Value
  val asc = Value("asc")
  val desc = Value("desc")

  def isOrderType(s: String) = values.exists(_.toString == s)
}

And use it:

Order.isOrderType("asc")  //> res0: Boolean = true
Order.isOrderType("foo")  //> res1: Boolean = false

Upvotes: 27

Related Questions