Nithin Chandy
Nithin Chandy

Reputation: 707

Searching inside an enum of Strings

How can we search for a string in an enum of strings?

object FilterByDimensions extends Enumeration {
  type FilterByDimensions = String
  val Instance = "Instance"
  val Platform = "Platform"
  val Region = "Region"

  def isSupported(s: String) = 
  FilterByDimensions.values.exists(_.toString.equalsIgnoreCase(s))
}

This method is not working. Tried this also.

def isSupported(s: String) = 
  FilterByDimensions.values.exists(_.equalsIgnoreCase(s))

Upvotes: 0

Views: 527

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

If I understand your question that you want to check if a string exists in FilterByDimension enum, the your FilterByDimension should be as below

object FilterByDimensions extends Enumeration {
  type FilterByDimensions = String
  val Instance = Value("Instance")
  val Platform = Value("Platform")
  val Region = Value("Region")

  import scala.util.control.Breaks._
  def isSupported(s: String) = {
    var exists = false
    breakable {
      for(value <- FilterByDimensions.values){
      exists = s.equalsIgnoreCase(FilterByDimensions(value.id).toString)
      if(exists){
        break
      }
    }
    }
    exists
  }
}

Edited
for pattern matching, its better to use case class

case class FilterByDimensions(value: String)

object FilterByDimensions {
  object Instance extends FilterByDimensions("Instance")
  object Platform extends FilterByDimensions("Platform")
  object Region extends FilterByDimensions("Region")

  val values = Seq(Instance, Platform, Region)
}

And you can call it as below

val ins = "Instance"
    ins match {
      case FilterByDimensions.Instance.value => println("instance match")
      case FilterByDimensions.Instance.value => println("progressing")
      case FilterByDimensions.Instance.value => println("region match")
      case _ => println("doesn't match")
    }

Upvotes: 1

som-snytt
som-snytt

Reputation: 39577

Maybe you're looking for:

scala> object X extends Enumeration { val Y = Value }
defined object X

scala> def f(s: String) = util.Try(X.withName(s)) match { case util.Success(X.Y) => "ok" case _ => "nope" }
f: (s: String)String

scala> f("Y")
res0: String = ok

scala> f("Z")
res1: String = nope

The two little features people request is matching by name and look-up by name which doesn't throw.

Upvotes: 1

Related Questions