Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

scala

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

like image 336
ilansch Avatar asked Mar 23 '14 10:03

ilansch


People also ask

How do you check if a string is present in an enum?

EnumUtils class of Apache Commons Lang. The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.

How do you check if a string is in a enum C#?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false.

Can enum contains string?

No they cannot. They are limited to numeric values of the underlying enum type.


1 Answers

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
like image 76
Lauri Avatar answered Sep 21 '22 15:09

Lauri